InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

3Sum

medium Original ↗ 00:00

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 gives you two things: 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`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug