Blind 75 · Two Pointers

3Sum

Medium

Watch the walkthrough (5:57)

Problem

Given an integer array nums, return every distinct triplet of values that sums to zero.
Each triplet must use three different positions in nums, and two triplets that hold the same three values are the same triplet, however many ways they can be picked.
The triplets may be returned in any order, and so may the three values inside each triplet, but no triplet may appear twice. If no triplet sums to zero, return an empty list.

Examples

Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: [-1,0,1] can be formed two ways but counts once.

Example 2:
Input: nums = [0,1,1]
Output: []

Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]

Example 4:
Input: nums = [-2,0,1,1,2]
Output: [[-2,0,2],[-2,1,1]]

Constraints

3 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5

Prerequisites

Two pointers — one pass with an index at each end, and the argument for why moving one of them cannot lose the answer.

How to think about it

1. Sort, Then Two Pointers Optimal

Intuition

Sorting does two jobs at once: it puts equal values next to each other, so a repeated triplet can be skipped without a set, and it turns "find two numbers summing to -x" into a two-pointer walk. Fix the smallest element, then close the remaining pair from both ends — a sum that is too small can only be helped by moving the left pointer up, too large by moving the right pointer down.

Algorithm

1. Sort the array.
2. For each index i, skip it if it repeats the previous value — that would repeat a triplet.
3. Walk left and right pointers over the rest, summing with nums[i].
4. Too small: move left up. Too large: move right down. Zero: record it, unless left has moved and repeats the previous value — that is the triplet just recorded.
5. After a zero, recorded or not, move left up once; the next turn moves right if it has to.

Time & Space

Time O(n^2) — a linear two-pointer pass for each of n starting elements, after an O(n log n) sort. Space O(1) beyond the output and the sort, which may use up to O(n) of its own in either language.