3Sum

35 min · threeSum()

A ledger can hold dozens of ways to pick three entries that cancel to zero. Your answer should describe the value combinations, not every set of positions that produced them.

Given an integer array nums, return every unique triplet of values whose sum is zero.

A few ground rules keep the output unambiguous:

  • Each triplet must come from three different positions in nums.
  • Write every returned triplet as [a, b, c] with a <= b <= c.
  • Return each value triplet once, even when duplicate values create it from many sets of positions.
  • The outer list may place the triplets in any order.

That sorted inner shape is the triplet's canonical form — one standard representation that makes value duplicates easy to recognize.

Constraints

  • 3 <= nums.length <= 3_000
  • -100_000 <= nums[i] <= 100_000

Hints

Start with positions

Three nested loops can inspect every i < j < k. If a sum is zero, sort those three values before adding them to a set so repeated value triplets collapse.

Sort the whole search space

Once nums is sorted, fix one value at index i. The other two values must add to -nums[i], which turns the rest of the work into a two-pointer search.

Skip duplicates where they arise

Skip a fixed value when it matches the previous fixed value. After finding a triplet, move both pointers past every copy of the values they just used.

Follow-up

Can you reach O(n²) time without using a set to remove duplicate triplets afterward?

Visible cases

Examples

Example 1

ready
Input
nums = [
  -1,
  0,
  1,
  2,
  -1,
  -4
]
Expected
[
  [
    -1,
    -1,
    2
  ],
  [
    -1,
    0,
    1
  ]
]
Why
duplicate -1 values still produce each value triplet only once

Example 2

ready
Input
nums = [
  0,
  0,
  0,
  0
]
Expected
[
  [
    0,
    0,
    0
  ]
]
Why
four zeros create several index choices but one value triplet

Example 3

ready
Input
nums = [
  1,
  2,
  -2,
  -1
]
Expected
[]
Why
no choice of three values sums to zero

Interview signal

Asked at

AmazonMetaGoogleAdobe
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite