LearnWithKiriti

4Sum

Medium LeetCode 18 ↗ 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 3: 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 Quad
  3. Better: Hash Set
  4. Optimal: Sort And Two Pointers
  5. Follow-up: K Sum

Revision notes

4Sum (online-test style)

Video: “4Sum” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 18. LeetCode 18, Medium. Taught as an online coding test: brute, better and optimal rounds, then the k-Sum follow-up, and each fast answer grows out of the slow one.

Return every quadruplet [a, b, c, d] from four different positions of nums with a + b + c + d == target. Each quadruplet only once, in any order.

nums = [1, 0, -1, 0, -2, 2], target = 0   ->   [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
nums = [2, 2, 2, 2, 2],      target = 8   ->   [[2, 2, 2, 2]]
Folder Approach Time Extra space
Brute-EveryQuad/ first, second, third, fourth, each after the one before; 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 and second; the rest is Two Sum: need = target - nums[first] - nums[second] - nums[third], look it up in seen (emptied for every pair), then add nums[third] O(n³) O(n)
Optimal-SortAndTwoPointers/ Sort; fix first and second, squeeze left and right: too small → left up, too big → right down; skip repeated first, second, left and right O(n³) O(1)
FollowUp-KSum/ Any k: sort once, kSum fixes one number (pick) and asks kSum for k - 1 numbers after it; at k = 2 it is the squeeze O(n^(k-1)) O(k) for the calls

Rebuild it

Fix two. Squeeze the rest. Skip the repeats, mind the overflow.

  • What do I fix? Two cards, first and second. The rest is the Two Sum II squeeze with target target - nums[first] - nums[second].
  • Which four repeats do I skip? first equal to the one before; second equal to the one before, but only when second > first + 1 (the first second after first may equal it: [2, 2, 2, 2] needs that); after a hit, left equal to the one before and right equal to the one after.
  • Overflow: four numbers near a billion add up to about four billion, more than a Java / C++ int can hold, so the sum wraps to a wrong number and a test fails (LeetCode has one: [1000000000 x4], target -294967296, answer []). Do the sum in long (Java) / long long (C++). Four ints always fit in a long. Python integers grow as big as they need; JavaScript numbers are exact up to about 9 quadrillion, so they are safe here.
  • When is long not enough? When numbers are multiplied, products can pass even a long; then Java’s BigInteger (Python needs nothing) is the general tool. For sums of a few ints, long is enough and much faster.
  • Why the squeeze never misses: if the sum is too small, nums[left] with ANY card up to right is too small, so drop left (mirror for too big).
  • k-Sum: 2Sum = squeeze, 3Sum = fix one + squeeze, 4Sum = fix two + squeeze, k-Sum = fix k - 2 + squeeze. Each fixed number costs one more factor of n: O(n^(k-1)). In kSum, pick > start is the same rule as second > first + 1.
  • Imports not allowed in your test? Drop import java.util.*; and write java.util. before List, Set, HashSet, ArrayList, Arrays and Collections.

Practise it on learnwithkiriti.com (notes, code in 4 languages, Memory Pairs level 3, 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 Quad

R1 Brute: every quad

found = empty set
for each first:
    for each second after first:
        for each third after second:
            for each fourth after third:
                sum = the four numbers (in long)
                if sum == target: sort the four, add to found
return everything in found

Why each loop starts after the one before: four different positions, and each group of positions is tried once. Why a set: [1, 0, -1, 0, -2, 2] has two 0 cards, and a sorted quad always looks the same, so the set keeps it once. Overflow: with plain int, [1000000000 x4] and target -294967296 wrongly finds a quad (the sum wraps); in long it is []. Check on example 1: 6 cards = 6 × 5 × 4 × 3 ÷ 24 = 15 tries, 3 quads. Complexity: O(n⁴) time, the set for space.

FourSumBrute.java
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        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++) {
                    for (int fourth = third + 1; fourth < nums.length; fourth++) {
                        // long: four big ints can go past the int limit (overflow)
                        long sum = (long) nums[first] + nums[second]
                            + nums[third] + nums[fourth];
                        if (sum == target) {
                            List<Integer> quad = Arrays.asList(
                                nums[first], nums[second], nums[third], nums[fourth]);
                            Collections.sort(quad);
                            found.add(quad);
                        }
                    }
                }
            }
        }
        return new ArrayList<>(found);
    }
}
better

Better: Hash Set

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

found = empty set
for each first:
    for each second after first:
        seen = empty set
        for each third after second:
            need = target - nums[first] - nums[second] - nums[third]   (in long)
            if need in seen: sort the four, add to found
            add nums[third] to seen
return everything in found

Derivation: in the brute, once first, second and third are fixed, fourth walks the rest of the row looking for ONE number, need. That is Two Sum, so remember the cards third has passed. Two rules: seen empties for every (first, second) pair (it holds only cards after second), and check BEFORE you add (a card can’t pair with itself). Check on example 1: 6 cards = 6 × 5 × 4 ÷ 6 = 20 checks; found still throws the repeats away. Complexity: O(n³) time, O(n) extra space for seen (plus the set).

FourSumBetter.java
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Set<List<Integer>> found = new HashSet<>();
        for (int first = 0; first < nums.length; first++) {
            for (int second = first + 1; second < nums.length; second++) {
                Set<Long> seen = new HashSet<>();
                for (int third = second + 1; third < nums.length; third++) {
                    // long: the subtraction can go past the int limit (overflow)
                    long need = (long) target - nums[first]
                        - nums[second] - nums[third];
                    if (seen.contains(need)) {
                        List<Integer> quad = Arrays.asList(
                            nums[first], nums[second], nums[third], (int) need);
                        Collections.sort(quad);
                        found.add(quad);
                    }
                    seen.add((long) nums[third]);
                }
            }
        }
        return new ArrayList<>(found);
    }
}
optimal

Optimal: Sort And Two Pointers

R3 Optimal: sort, fix two, squeeze, skip the repeats

sort nums
quads = empty list
for each first, up to the fourth from the end:
    same as the one before? skip
    for each second after first, up to the third from the end:
        second > first + 1 and same as the one before? skip
        left = second + 1;  right = last
        while left < right:
            sum = the four numbers (in long)
            too small: left up;  too big: right down
            equal: add the quad, left up, right down
                skip equal numbers: left up, right down
return quads

Derivation: the set exists only to throw repeats away, and seen costs memory. Sort the row: repeats sit side by side (skip “same as my neighbour”), and the squeeze from Two Sum II needs no memory. Why second > first + 1: the first second right after first may hold the same number ([2, 2, 2, 2] needs two 2s). Only a LATER equal second is a repeat. Dry run on example 1, sorted [-2, -1, 0, 0, 1, 2], target 0: first -2 finds [-2, -1, 1, 2] and [-2, 0, 0, 2], then the second 0 as second: skip. First -1 finds [-1, 0, 0, 1], second 0 again: skip. 7 looks, 3 quads. Example 2, [2, 2, 2, 2, 2], target 8: one look finds [2, 2, 2, 2]; the next second (a 2, not first + 1) skips; the next first (a 2) skips. Complexity: O(n³) time, O(1) extra space apart from the answer.

FourSumOptimal.java
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> quads = new ArrayList<>();
        for (int first = 0; first < nums.length - 3; first++) {
            // same first number as last time: its quads are already found
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            for (int second = first + 1; second < nums.length - 2; second++) {
                // second may equal first once (2, 2, ...); after that an equal second is a repeat
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                int left = second + 1;
                int right = nums.length - 1;
                while (left < right) {
                    // long: four big ints can go past the int limit (overflow)
                    long sum = (long) nums[first] + nums[second]
                        + nums[left] + nums[right];
                    if (sum < target) {
                        left++;
                    } else if (sum > target) {
                        right--;
                    } else {
                        quads.add(Arrays.asList(
                            nums[first], nums[second], nums[left], nums[right]));
                        left++;
                        right--;
                        // skip repeats so the same group is not added twice
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }
            }
        }
        return quads;
    }
}
follow-up

Follow-up: K Sum

Follow-up: k-Sum (any k)

fourSum(nums, target):
    sort nums
    return kSum(nums, target, start = 0, k = 4)

kSum(nums, target, start, k):
    groups = empty list
    if k == 2:
        squeeze left = start, right = last (skip repeats after a hit)
        return the pairs
    for each pick from start, leaving room for k - 1 more:
        pick > start and same as the one before? skip
        for each rest in kSum(nums, target - nums[pick], pick + 1, k - 1):
            add [nums[pick]] + rest to groups
return groups

Derivation: 3Sum fixed one number and ran Two Sum; 4Sum fixed two. Every level does the same job: fix one number, then solve the same problem with one number fewer. So write that job once and let it call itself until two numbers are left. pick > start is the same rule as second > first + 1: the first pick at a level may equal the number before it. No backtracking list to undo: each call returns finished groups and the caller puts its own number in front. Complexity: O(n^(k-1)) time (k - 2 fixed numbers, then an O(n) squeeze), O(k) for the calls. k = 4 gives O(n³).

FourSumKsum.java
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        return kSum(nums, target, 0, 4);
    }

    private List<List<Integer>> kSum(int[] nums, long target,
            int start, int k) {
        List<List<Integer>> groups = new ArrayList<>();
        // two numbers left: the Two Sum II squeeze
        if (k == 2) {
            int left = start;
            int right = nums.length - 1;
            while (left < right) {
                long sum = (long) nums[left] + nums[right];
                if (sum < target) {
                    left++;
                } else if (sum > target) {
                    right--;
                } else {
                    List<Integer> pair = new ArrayList<>();
                    pair.add(nums[left]);
                    pair.add(nums[right]);
                    groups.add(pair);
                    left++;
                    right--;
                    // skip repeats so the same group is not added twice
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                }
            }
            return groups;
        }
        for (int pick = start; pick < nums.length - k + 1; pick++) {
            // same rule as second > first + 1: the first pick may equal the number before it
            if (pick > start && nums[pick] == nums[pick - 1]) {
                continue;
            }
            for (List<Integer> rest
                    : kSum(nums, target - nums[pick], pick + 1, k - 1)) {
                rest.add(0, nums[pick]);
                groups.add(rest);
            }
        }
        return groups;
    }
}