~/problems / Two pointers

3Sum

medium ~25 min

Write three_sum(nums: list[int]) -> list[list[int]].

Return every distinct triple of values [a, b, c] that can be picked from three different positions of nums with a + b + c == 0. Two triples are the same if they contain the same values (as a multiset), so list each one once. Each triple should be sorted ascending; the list of triples may be in any order.

Example: nums = [2, -1, -1, 0, 1, -3] gives [[-3, 1, 2], [-1, -1, 2], [-1, 0, 1]]. [0, 0, 0, 0] gives [[0, 0, 0]]; [1, 2] gives [].

Constraints: 0 <= len(nums) <= 1500; values are in [-10^6, 10^6].

Aim for O(n²). The O(n³) triple loop is too slow for the large test.

Show hint

once the values are sorted and the smallest element of a triple is fixed, the other two can be found by moving inward from both ends of the rest. Skipping repeated values keeps each triple from appearing twice.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc