You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* This algorithm finds all unique triplets in an array of integers that sum up to zero.
9
+
* It uses a two-pointer approach on a sorted version of the array to efficiently find the triplets.
10
+
*
11
+
* ### How it works:
12
+
* 1. The input array is sorted to enable the two-pointer approach and to handle duplicates easily.
13
+
* 2. We iterate through the array with a single pointer `i`.
14
+
* 3. For each element `nums[i]`, we use two more pointers, `left` (starting at `i+1`) and `right` (starting at the end of the array).
15
+
* 4. We calculate the sum of the three elements. If the sum is zero, we've found a triplet. If it's less than zero, we move `left` forward. If it's greater, we move `right` backward.
16
+
* 5. Duplicates are skipped to ensure that each unique triplet is only added once.
17
+
*
18
+
* ### Complexity
19
+
* - **Time Complexity:** O(n^2), where 'n' is the number of elements. The array sort is O(n log n), but the nested loop structure (a `for` loop and a `while` loop) dominates.
20
+
* - **Space Complexity:** O(1) for the algorithm itself (if we don't count the space for the output list). Sorting is done in-place.
0 commit comments