Question
Given an integer array nums, return all the tripletsÂ
[nums[i], nums[j], nums[k]]
 such thatÂi != j
,Âi != k
, andÂj != k
, andÂnums[i] + nums[j] + nums[k] == 0
.Notice that the solution set must not contain duplicate triplets.
This is atwo_pointers question.
Idea
- Sort input array
- Iterate through input array
- Establish l, r pointers
- If i > 0, check if our current num is the same as the last index, then skip if true to avoid duplicates
While our pointers do not overlap
- Sum current a value with b and c from l, and r
- Check value, if greater than 0, reduce r, if less than 0, increment l,
- Else:
- Add combination to res, increment l to try to find another combination
- While our new nums[l] is the same as our old nums[l] and l < r, increment l to prevent duplicates
- Return res