LearnWithKiriti

3Sum

Medium LeetCode 15 ↗ GitHub ↗
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end. 🎮 Play Memory Pairs: Level 2: a mini-game built on this problem. Works on your phone too. Pass Submit to unlock every round.
Play
On this page
  1. Revision notes
  2. Brute: Every Triplet
  3. Better: Hash Set
  4. Optimal: Sort And Two Pointers

Revision notes

3Sum (online-test style)

Video: “3Sum” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 17. LeetCode 15, Medium. Taught as an online coding test: three rounds, 5:00 on the clock while typing each (15 minutes), and the fast answer grows out of the slow one.

Return every triplet [a, b, c] from three different positions of nums with a + b + c == 0. Each triplet only once, in any order.

nums = [-1, 0, 1, 2, -1, -4]           ->   [[-1, -1, 2], [-1, 0, 1]]
nums = [2, 4, -4, -3, 6, 0, -3, -3, 4] ->   [[-4, 0, 4], [-3, -3, 6]]   (the video's nine cards)
Folder Approach Time Extra space
Brute-EveryTriplet/ first, second after it, third after that; a hit is sorted and stored in a set found, so a repeat lands on the copy already there O(n³) the set
Better-HashSet/ Fix first; the rest is Two Sum: need = -(nums[first] + nums[second]), look it up in seen (emptied for every first), then add nums[second] O(n²) O(n)
Optimal-SortAndTwoPointers/ Sort; for each first squeeze left and right: too small → left up, too big → right down; skip repeated first, left and right O(n²) O(1)

Rebuild it

Fix one. Two Sum the rest. Sort, squeeze, skip the repeats.

  • What do I fix? One card, first. The rest is Two Sum with target -nums[first].
  • Why a set in rounds 1 and 2? A triplet is sorted before it is stored, so the same three numbers always look the same; the set’s hash code + equals keep it once (Java HashSet of List, Python set of tuples, C++ set of vectors, JavaScript Map keyed by the joined text).
  • What does sorting buy me? Two things: the squeeze, so no memory, and equal numbers side by side, so no set.
  • Why the squeeze never misses: if nums[first] + nums[left] + nums[right] is too small, nums[left] with ANY card up to right is too small, so drop left (mirror for too big). For one first on nine cards, that is at most 7 looks instead of 28 pairs.
  • Which three repeats do I skip? first equal to the one before; after a hit, left equal to the one before and right equal to the one after. Each is one while loop (or a continue).
  • Bonus (not in the code): once nums[first] > 0, three numbers that big can’t make zero, so you could stop early.
  • Imports not allowed in your test? Drop import java.util.*; and write java.util. before List, Set, HashSet, ArrayList, Arrays and Collections.
  • The ladder: 2Sum finds a pair, 3Sum = fix one + Two Sum, 4Sum = fix two + Two Sum.

Practise it on learnwithkiriti.com (notes, code in 4 languages, Memory Pairs level 2, a mock interview with Mr. Tock, Shelf Bot animates your own code), or next to the video in the Kodee Practice Chrome extension (link in the video description).

See the pseudocode.md in each folder. Every program was compiled, run and tested.

brute

Brute: Every Triplet

R1 Brute: every triplet

found = empty set
for each first from 0:
    for each second after first:
        for each third after second:
            if nums[first] + nums[second] + nums[third] == 0:
                sort the three, add to found
return everything in found

Why each loop starts after the one before: no position is used twice, and each group of three positions is tried once. Why sort before storing: -1, 0, 1 and 0, 1, -1 are the same triplet; sorted, they look the same, so the set keeps one. Check on the nine cards [2, 4, -4, -3, 6, 0, -3, -3, 4]: 84 tries, 5 hits, 2 kept ([-4, 0, 4] and [-3, -3, 6]); the other 3 hits are repeats the set throws away. Cost: n × (n − 1) × (n − 2) ÷ 6 tries. 9 cards = 84. O(n³) time, the set is extra space.

ThreeSumBrute.java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> found = new HashSet<>();
        for (int first = 0; first < nums.length; first++) {
            for (int second = first + 1; second < nums.length; second++) {
                for (int third = second + 1; third < nums.length; third++) {
                    if (nums[first] + nums[second] + nums[third] == 0) {
                        // sorted, so the same three numbers always look the same
                        List<Integer> triplet = Arrays.asList(nums[first], nums[second], nums[third]);
                        Collections.sort(triplet);
                        found.add(triplet);
                    }
                }
            }
        }
        return new ArrayList<>(found);
    }
}
better

Better: Hash Set

R2 Better: fix first, then Two Sum with a hash set

found = empty set
for each first from 0:
    seen = empty set
    for each second after first:
        need = -(nums[first] + nums[second])
        if need in seen: sort the three, add to found
        add nums[second] to seen
return everything in found

Derivation: in one row of the brute, first and second are fixed and third walks the whole rest of the row looking for ONE number: minus first, minus second. That is Two Sum with target minus first, so remember the cards second has passed. Two rules: seen empties when first moves (earlier cards already had their turn as first), and check BEFORE you add (a card can’t pair with itself). What a hash set is: an array of slots. A formula turns a number into a hash code, which picks one slot; to check a number, the same formula jumps straight to that slot. Two numbers in one slot is a collision: the slot keeps both and equals tells them apart. O(1) on average. Check on the nine cards: 36 checks, 5 hits, 2 kept; found still throws the repeats away. Complexity: O(n²) time, O(n) extra space for seen (plus the set).

ThreeSumBetter.java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> found = new HashSet<>();
        for (int first = 0; first < nums.length; first++) {
            // Two Sum on the numbers after first, with target -nums[first]
            Set<Integer> seen = new HashSet<>();
            for (int second = first + 1; second < nums.length; second++) {
                int need = -(nums[first] + nums[second]);
                if (seen.contains(need)) {
                    List<Integer> triplet = Arrays.asList(nums[first], nums[second], need);
                    Collections.sort(triplet);
                    found.add(triplet);
                }
                seen.add(nums[second]);
            }
        }
        return new ArrayList<>(found);
    }
}
optimal

Optimal: Sort And Two Pointers

R3 Optimal: sort, squeeze, skip the repeats

sort nums
triplets = empty list
for each first, up to the third from the end:
    same as the one before? skip
    left = first + 1;  right = last
    while left < right:
        sum = nums[first] + nums[left] + nums[right]
        too small: left up;  too big: right down
        zero: add the triplet, left up, right down
            skip equal numbers: left up, right down
return triplets

Derivation: the repeats came from equal numbers far apart (three -3s, two 4s). Sort the row and they sit side by side, so a repeat is “same as my neighbour? skip”. A sorted row also gives Two Sum II’s squeeze, so seen goes too. Why the squeeze never misses: too small means left with every card up to right is too small, so left is useless: drop it. Too big works the other way for right. Why it is faster: for one first on nine cards, the brute tries 28 pairs of the cards after it; the squeeze drops one card per look, at most 7. Sorting costs n log n once, and we return numbers, not positions, so the new order is fine. Dry run on the sorted cards [-4, -3, -3, -3, 0, 2, 4, 4, 6]: first -4 squeezes to [-4, 0, 4], then right lands on the other 4: skip. First -3 finds [-3, -3, 6], then left lands on another -3: skip. The next two -3s as first: skip. First 0, 2 and 4 find nothing. Two triplets, 15 looks, no memory, no set. Bonus (not in the code): once nums[first] > 0, stop early. Complexity: O(n²) time, O(1) extra space apart from the answer.

ThreeSumOptimal.java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> triplets = new ArrayList<>();
        for (int first = 0; first < nums.length - 2; first++) {
            // same first number as last time: its triplets are already found
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int left = first + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[first] + nums[left] + nums[right];
                if (sum < 0) {
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    triplets.add(Arrays.asList(nums[first], nums[left], nums[right]));
                    left++;
                    right--;
                    // skip repeats so the same triplet is not added twice
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                }
            }
        }
        return triplets;
    }
}