Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that i, j, k are distinct and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.
Sort first. Fix one element nums[i], then use two pointers on the remaining subarray to find pairs summing to -nums[i]. Sorting lets us skip duplicates cleanly ā if nums[i] == nums[i-1], we'd get the same triplets again.
Sorting enables two pointers AND makes duplicate skipping trivial.
For each i from 0 to n-3: skip if nums[i] == nums[i-1] (duplicate). Set lo=i+1, hi=n-1. Move pointers: if sum < 0, lo++; if sum > 0, hi--; if sum == 0, record and skip duplicates on both sides.
Sorting is O(n log n). The outer loop is O(n), inner two-pointer is O(n) ā total O(n²). Output space doesn't count as extra.
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue # skip duplicate i
lo, hi = i + 1, len(nums) - 1
while lo < hi:
total = nums[i] + nums[lo] + nums[hi]
if total < 0:
lo += 1
elif total > 0:
hi -= 1
else:
result.append([nums[i], nums[lo], nums[hi]])
while lo < hi and nums[lo] == nums[lo+1]: lo += 1
while lo < hi and nums[hi] == nums[hi-1]: hi -= 1
lo += 1; hi -= 1
return resultWhat pattern do you think this problem uses?