CodingNodes / Two Pointers / 3Sum System design Space play · ←→ step · R restart

Problem

Given an integer array nums, find every set of three numbers taken from different positions whose sum is exactly 0.

The answer must not contain the same triplet twice. Triplets may be returned in any order, and each triplet is listed here in increasing order. If there are none, return an empty list.

Constraints

  • 3 ≤ nums.length ≤ 3000
  • −10⁵ ≤ nums[i] ≤ 10⁵

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(1) extra

Time: Sorting costs O(n log n). For each of the n first numbers, the two pointers sweep the rest of the array once, which is O(n), so O(n²) overall.

Space: Apart from the sorted copy and the output, only a few integer variables are used.

Sort the array. Fix one number at index i, then use left and right on the rest. A sum below zero needs a bigger number, so move left up. A sum above zero needs a smaller one, so move right down. Skip equal neighbours to avoid repeated triplets.