This problem follows the Sort + Two Pointers pattern, commonly found in the Two Pointers category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Sort array. Fix one element, use two pointers for the remaining pair. Skip duplicates.
Sorting first lets you use two pointers for the inner loop AND skip duplicates easily — without sorting you'd need a set of tuples.
sort(nums)
for i = 0 to n - 2:
if i > 0 and nums[i] == nums[i-1]: continue
left = i + 1, right = n - 1
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum < 0: left++
else if sum > 0: right--
else:
result.add([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]: left++
while left < right and nums[right] == nums[right-1]: right--
left++; right--Practice 3Sum and similar Two Pointers problems with flashcards. Build pattern recognition through active recall.
Practice this problem