Skip to content

3Sum

MediumLeetCode #15Time O(n²)Space O(n)

You get an array of integers. Return every set of three numbers (from three different positions) whose sum is 0. The result must not contain the same triplet twice, and the order of triplets or of numbers inside one doesn’t matter.

nums = [-1, 0, 1, 2, -1, -4] -> [[-1, -1, 2], [-1, 0, 1]]

Brute force checks all triplets: O(n³). Fixing one number turns the rest into Two Sum: find two numbers that add to -nums[i].

Sort the array first. Then for each i, put one pointer just after i and one at the end. If the three-number sum is too small, move left up. If it is too big, move right down. If it is zero, record it and move both. Sorting also puts equal numbers side by side, so duplicates are easy to skip: ignore an i equal to the previous i, and after a hit, skip repeated values for left.

Show solutionHide solution
def three_sum(nums: list[int]) -> list[list[int]]:
nums = sorted(nums)
result = []
for i in range(len(nums) - 2):
if nums[i] > 0:
break # smallest is positive, so no triplet can sum to 0
if i > 0 and nums[i] == nums[i - 1]:
continue # same first number as last time
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1 # skip duplicate second numbers
return result
  • Time: O(n²) — sorting is O(n log n); then each of n choices of i runs a linear two-pointer scan.
  • Space: O(n) — the sorted copy (the output list is not counted). Sorting the input in place would leave only the sort’s own stack space, usually O(log n); say so if asked.
  • Duplicates are the hard part. Skip repeated i values, and after recording a triplet skip repeated left values. Skipping right too is optional: once left moves to a new value, the sum changes and the right duplicates get passed naturally.
  • Compare against the previous i, not the next one. nums[i] == nums[i - 1] keeps the first occurrence, so [-1, -1, 2] is still found.
  • Don’t use a set of triplets as a shortcut. It works but costs extra memory and hides that you understand the sorted skip.
  • Early exit. Once nums[i] > 0 no later triplet can sum to zero.

Return the sum of three numbers closest to a target. The trick: same sort and fixed i with two pointers, but track the sum with the smallest distance to the target instead of collecting exact hits. Return immediately on an exact match.

Find unique quadruplets that sum to a target. The trick: sort, add one more outer loop, then run the two-pointer scan inside. Skip duplicates at both outer loops. O(n³).

Two Sum II - Input Array Is Sorted (LeetCode 167)

Section titled “Two Sum II - Input Array Is Sorted (LeetCode 167)”

The one-level version: a single pair in a sorted array. The trick: the inner two-pointer loop used here, with no outer loop and no duplicates to skip.