15. 3Sum
https://leetcode.com/problems/3sum/description/
Optimal Space & Time Complexity
Solutions
東
Hao
YC
SOL
Supplement / Discussion
東
Hao
JavaScript with lots of explanatory comments!
"Three" pointers: employ indexs i
, j
, k
to indicate the number. Iterate i
with the following steps:
- Fix
i
first, and so we have only two pointers j
, k
left.
- Sum up
i
, j
, k
to see if reach targetSum
while move j
and k
closer to each other
- Add early break/continue during iterations
- When
nums[i] > targetSum
- When
nums[i] === nums[i - 1]
- When
nums[j] === nums[j - 1]
- When
nums[k] === nums[k - 1]
YC
- sort the array
- set three variables:
i
, left
, right
i
is a for-loop variable
left
and right
serve as left-right pointer
- remove duplicate triplets
nums[i] === nums[i-1]
nums[left] === nums[left-1]
nums[right] === nums[right+1]
- (nice to have) early return
nums.length < 3
nums[i] > 0
: because the array is sorted
SOL
3 loops 👎🏻👎🏻👎🏻
[-1,0,1,2,-1,-4]
- Sort the input array in ascending order
[-4,-1,-1,0,1,2,]
- Loop through each value in the array.
- Calculate the target value needed for two additional elements to sum up to zero.
- Iterate through each value in sub-array1 (remaining elements after current value).
-4, [-1,-1,0,1,2,] find a + b = 4
- Calculate the value needed for the third element to complete the triplet sum.
- Iterate through each value in sub-array2 (remaining elements after current value).
- Search for the value in the sub-array2 that matches the calculated target value.
- Add the triplet [a, b, c] to the result array if found.
-1, [,-1,0,1,2,] find 1
…
two poniters 👍👍👍
- Sort the input array in ascending order.
- Loop through the array, excluding the last two elements.
- Skip duplicates.
- Use a two-pointers approach (left-right pointers) that move toward each other.
- Calculate the sum
- If the sum === target:
a. Add the triplet to the result array.
b. Eliminate duplicate pointers by moving them.
c. Move both pointers.
- If sum < target, move leftPointer.
- If sum > target, move rightPointer.
Supplement (psuedo code from YC)