InterviewPrepKit

Home / Coding / Two Pointers

3Sum

medium Original β†—
Solving tips
  • Sort first, then fix an anchor i and run converging two pointers on the suffix; this hits the O(n^2) target versus O(n^3) brute force.
  • Dedupe on values, not indices: skip an anchor equal to its predecessor, and after recording a hit step both pointers past equal neighbors.
  • When the triplet sum is too small move left up, too big move right down, equal record and move both inward.
  • Break early once nums[i] > 0 (no zero-sum possible in ascending order); O(1) extra space beyond sort and output.

Problem

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] with three distinct indices (i != j, i != k, j != k) whose values sum to exactly 0.

The answer must not contain duplicate triplets: two triplets that contain the same three values (in any order) count as the same triplet and may appear only once. The triplets themselves may be returned in any order.

Examples

  • nums = [-1,0,1,2,-1,-4] β†’ [[-1,-1,2],[-1,0,1]] -1 + -1 + 2 = 0 and -1 + 0 + 1 = 0; the second -1 in the input does not create a duplicate [-1,0,1].
  • nums = [0,1,1] β†’ [] No three values sum to zero.
  • nums = [0,0,0,0] β†’ [[0,0,0]] Four zeros yield the triplet [0,0,0] exactly once, despite many index combinations.

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
  • With n = 3000, O(n^3) β‰ˆ 2.7 * 10^10 is far too slow; O(n^2) β‰ˆ 9 * 10^6 is the target.

Think about it first

Hint 1 Fix the first element `a`. The rest of the problem becomes: find two other elements summing to `-a` β€” a Two Sum subproblem inside a loop.
Hint 2 Sorting the array costs only `O(n log n)` and buys you two things at once: a way to find pairs by moving pointers, and a way to skip duplicates by skipping equal neighbors.
Hint 3 After sorting, for each anchor index `i`: run `left = i + 1`, `right = n - 1`; if the three sum below zero move `left` up, above zero move `right` down, equal β€” record and step both past all equal neighbors. Also skip anchors equal to their previous value, and stop early once `nums[i] > 0`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.