# 3Sum

[link](https://leetcode.com/problems/3sum/) · Medium · `array`, `two pointers`, `sorting`

> k-Sum → sort, fix the first k − 2 numbers in loops, finish with a two-pointer scan (Two Sum II). 3Sum is O(n^2), 4Sum O(n^3). For "no duplicate tuples", don't collect into a set — skip equal neighbours after sorting: at each fixed position compare with the previous value, and after a match move the pointer past all its copies.

## Problem

> Given an integer array `nums`, return all the triplets `[nums[i], nums[j], nums[k]]` where
> `nums[i] + nums[j] + nums[k] == 0`, and the indices `i`, `j` and `k` are all distinct.
> The output should **not contain any duplicate triplets**. You may return the output and the
> triplets in any order.

**Example 1**
```
Input:  nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
```
`(-1) + 0 + 1`, `0 + 1 + (-1)` and `(-1) + 2 + (-1)` all sum to 0; the distinct triplets are
`[-1,0,1]` and `[-1,-1,2]`.

**Example 2**
```
Input:  nums = [0,1,1]
Output: []
```
The only possible triplet does not sum to 0.

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

**Constraints**
- `3 <= len(nums) <= 3000`
- `-10^5 <= nums[i] <= 10^5`

## Thinking

- **Brute force idea:** try every triple `i < j < k` and put the sorted triplet in a set to drop
  duplicates, $O(n^3)$ time. With $n = 3000$ that's ~4.5 billion triples — far too slow.
- **Key insight:** **sort first**, then fix the smallest number `nums[i]` and the problem becomes
  Two Sum II (#167) on the rest: find `nums[left] + nums[right] == -nums[i]` with two pointers
  from both ends. Sum too small → `left += 1`; too big → `right -= 1`. That's $O(n)$ per `i`,
  $O(n^2)$ total, and the sort ($O(n \log n)$) is free next to it.
- **Duplicates are the hard part.** Sorting puts equal values next to each other, so skip them
  instead of deduplicating afterwards:
  - skip `nums[i]` if it equals the **previous** value `nums[i - 1]` (that value was already
    used as the first number, with a superset of the remaining choices);
  - after recording a triplet, move `left` past every copy of `nums[left]` (then `right` is forced
    to change too, since the sum must stay the same).
- **Quick reject / early stop:** once `nums[i] > 0`, all three numbers are positive and no
  later `i` can work → `break`.
- **Edge cases to remember:** all zeros (`[0,0,0,0]` → one triplet); two equal numbers inside
  the triplet (`[-1,-1,2]`); many copies producing the same triplet (`[-2,0,0,2,2]`); all
  positive / all negative (no answer); exactly 3 elements.

## Solution

### Approach A — my version: sort + two pointers, skipping duplicates ✅ best practice
**Complexity:** Time $O(n^2)$ · Space $O(1)$ extra (ignoring the sort and the output; sorts `nums` in place)

Already optimal. Sort, fix `nums[i]` (skipping values equal to the previous one), then run Two
Sum II on the rest with `target = -nums[i]`. After a match, both pointers move past their copies,
so no triplet is produced twice and no set is needed. The sort is $O(n \log n)$, small next to the
$O(n^2)$ scan. One small extra: `if nums[i] > 0: break` stops early, since three positives can't
sum to 0 (Approach B).

```python
def three_sum_mine(nums: list[int]) -> list[list[int]]:
    nums.sort()  # sorts the caller's list in place
    result = []

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:  # this first number was already tried
            continue
        left = i + 1
        right = len(nums) - 1
        target = -nums[i]
        while left < right:
            total = nums[left] + nums[right]

            if total > target:
                right -= 1
            elif total < target:
                left += 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                while left < right and nums[left] == nums[left + 1]:  # skip copies of nums[left]
                    left += 1
                while left < right and nums[right] == nums[right - 1]:  # skip copies of nums[right]
                    right -= 1
                left += 1
                right -= 1

    return result
```

### Approach B — same, with the early stop
**Complexity:** Time $O(n^2)$ · Space $O(1)$ extra

Approach A plus `if nums[i] > 0: break`. Once the smallest of the three numbers is positive,
no later `i` can reach 0. Same Big-O, and it skips the whole positive half of the array.
Skipping copies of only `nums[left]` is enough here: if `left` moves to a new value, the sum
changes, so `right` has to move anyway.

```python
def three_sum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    n = len(nums)
    result = []
    for i in range(n - 2):
        if nums[i] > 0:  # smallest of the three is positive -> no more answers
            break
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:  # skip copies
                    left += 1
    return result
```

### Approach C — sort + hash set per first number
**Complexity:** Time $O(n^2)$ · Space $O(n)$

Same outer loop, but the inner Two Sum uses a hash set (Two Sum I style) instead of two pointers:
walk `j` to the right and check whether `-nums[i] - nums[j]` was seen. Same Big-O, but it needs
extra memory and the duplicate handling is fiddlier. Useful when you can't sort — e.g. the
variant that returns indices.

```python
def three_sum_hashset(nums: list[int]) -> list[list[int]]:
    nums = sorted(nums)
    n = len(nums)
    result = []
    for i in range(n - 2):
        if nums[i] > 0:
            break
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        seen = set()
        j = i + 1
        while j < n:
            complement = -nums[i] - nums[j]
            if complement in seen:
                result.append([nums[i], complement, nums[j]])
                while j + 1 < n and nums[j] == nums[j + 1]:  # skip copies of nums[j]
                    j += 1
            seen.add(nums[j])
            j += 1
    return result
```

### Approach D — brute force with a set of triplets
**Complexity:** Time $O(n^3)$ · Space $O(\text{answers})$

Every combination of three, sorted into a tuple so the set drops duplicates. Too slow for
$n = 3000$, but obviously correct, so the tests use it as a reference on random inputs.

```python
from itertools import combinations


def three_sum_brute(nums: list[int]) -> list[list[int]]:
    found = {tuple(sorted(t)) for t in combinations(nums, 3) if sum(t) == 0}
    return [list(t) for t in found]
```

## Scratch / Experiments

Worst case for the $O(n^2)$ approaches: $n = 3000$ distinct values `-1500 … 1499`, so the early
`break` only kicks in halfway and there are ~1.7 million answers. The brute force would need
~4.5 billion triples there, so it's timed on $n = 150$ only.

Measured (one run), $n = 3000$: mine ~334 ms, with early stop ~278 ms, hash set ~409 ms.
At $n = 150$: brute force ~31 ms vs two pointers ~0.65 ms (~50×, and the gap grows with $n$).
All three $O(n^2)$ versions are close: the early `break` saves ~17% by skipping the positive half,
and the hash set is slowest because it hashes and allocates a new set for every `i`, where two
pointers only compares integers. Most of the time goes into building the ~1.7 million result lists.

```python
nums = list(range(-1500, 1500))
assert normalize(three_sum_mine(list(nums))) == normalize(three_sum_hashset(list(nums)))
%timeit -n 1 -r 3 three_sum_mine(list(nums))
%timeit -n 1 -r 3 three_sum(list(nums))
%timeit -n 1 -r 3 three_sum_hashset(list(nums))

small = list(range(-75, 75))  # n = 150 for the O(n^3) brute force
%timeit -n 1 -r 3 three_sum_brute(small)
%timeit -n 1 -r 3 three_sum(list(small))
```

## Takeaways

- **Pattern:** **k-Sum → sort, fix the first k − 2 numbers in loops, finish with a two-pointer
  scan** (Two Sum II). 3Sum is $O(n^2)$, 4Sum $O(n^3)$. For "no duplicate tuples", don't collect
  into a set — **skip equal neighbours** after sorting: at each fixed position compare with the
  *previous* value, and after a match move the pointer past all its copies.
- **Mistakes I made:** the final version is optimal; the only small improvement is the
  `nums[i] > 0` early `break`. My **first attempt** had three bugs (replayed in
  `test_first_attempt_bugs`), worth remembering:
  - Swapped the pointer moves. Say it out loud: *sum too small → make it bigger → move the left
    (small) pointer right*.
  - Skipped duplicates by looking **ahead** (`nums[i] == nums[i + 1]`). That throws away the first
    copy, which is the one that still has its twin to the right, so `[-1,-1,2]` was lost. Always
    look **back**: `i > 0 and nums[i] == nums[i - 1]`.
  - Only deduplicated the first number. The pair `(left, right)` can repeat too, so skip copies
    after recording a triplet.
  - Examples 2 and 3 pass even with all three bugs. Test with repeated values, and against a
    brute-force reference on random inputs.
  - `nums.sort()` mutates the caller's list; fine on LeetCode, but use `sorted(nums)` if the
    input must be kept.
- **Related problems:** Two Sum (#1, hash map, unsorted), Two Sum II (#167, the inner
  two-pointer scan), 3Sum Closest (#16, same scan, track the nearest sum), 4Sum (#18, one more
  outer loop), 3Sum Smaller (#259, count pairs: when the sum is small, all `right - left` pairs
  count), Valid Triangle Number (#611, sort + fix the largest + two pointers),
  Container With Most Water (#11, two pointers from both ends).

---

From https://taosu.blog/notes/0015-3sum
