1. Input Validation:
- The function
threeSumtakes an integer arrayarras its input. - It first checks if the array is null or if its length is less than 3. If either of these conditions is met, the function returns an empty list because you cannot form triplets with less than 3 elements.
2. Sorting:
- The input array
arris sorted in ascending order usingArrays.sort(arr). Sorting is a crucial step in solving the 3Sum problem, as it allows us to efficiently search for triplets.
3. Loop Over the Array:
- The code uses a for loop to iterate through the sorted array
arrfrom the beginning to the third-to-last element. The reason for iterating only up toarr.length - 2is that we need at least two more elements (one on the left and one on the right) to form a triplet.
4. Two-Pointer Approach:
- Inside the loop, two pointers,
leftandright, are initialized.leftstarts just to the right of the current element at indexi, andrightstarts at the last element of the array. - A while loop is used to perform a two-pointer approach to find triplets. It continues as long as
leftis less thanright.
5. Triplet Sum Calculation:
- Inside the while loop, the sum of the current triplet is calculated as
sum = arr[i] + arr[left] + arr[right].
6. Checking for Zero Sum:
- If
sumis equal to zero, it means that a triplet with a zero sum has been found. In this case:- The triplet (arr[i], arr[left], arr[right]) is added to the
resultset. A set is used to store unique triplets to avoid duplicates. - Both
leftandrightpointers are moved inward to find other potential triplets.
- The triplet (arr[i], arr[left], arr[right]) is added to the
7. Adjusting Pointers:
- If
sumis less than zero, it means that the sum is too small, so theleftpointer is moved to the right (increased). - If
sumis greater than zero, it means that the sum is too large, so therightpointer is moved to the left (decreased).
8. Returning the Result:
- Once the loop has finished processing all possible triplets, the function converts the
resultset to a list and returns it. This list contains all unique triplets that sum to zero.
9.Time Complexity :
The code’s time complexity is O(n^2) due to the nested loops and the sorting step, where “n” is the length of the input array arr. The use of a set ensures that duplicate triplets are not included in the result.