Visualize

Pattern visualizer

4Sum

Checking all four indices costs O(n^4). Sorting first collapses one whole dimension: once two indices are frozen, the rest is the classic sorted two-sum, where a sum that is too small can only be raised by abandoning the smallest value and one that is too large only lowered by abandoning the largest. Each discarded value is gone for good, so the tail scan is linear. Sorting also puts equal values next to each other, which is why duplicates can be skipped by a neighbour comparison instead of de-duplicating the answer list at the end. Animated on: nums = [1, 0, -1, 0, -2, 2], target = 0 — find every unique quadruplet that sums to the target..

Fix two indices, then run two-sum on the sorted tail

time O(n^3)space O(1) beyond the outputstep 1 / 16
1
[0]
0
[1]
-1
[2]
0
[3]
-2
[4]
2
[5]
line 1

nums = [1, 0, -1, 0, -2, 2], target = 0. Unsorted, nothing tells us which way to search: a sum that is too small could be fixed by swapping in any of the remaining values.

Pseudocode
1FUNCTION fourSum(nums, target)
2 SORT nums
3 FOR i <- 0 TO LENGTH(nums) - 4
4 IF i > 0 AND nums[i] = nums[i - 1] THEN CONTINUE
5 FOR j <- i + 1 TO LENGTH(nums) - 3
6 IF j > i + 1 AND nums[j] = nums[j - 1] THEN CONTINUE
7 l <- j + 1
8 r <- LENGTH(nums) - 1
9 WHILE l < r
10 s <- nums[i] + nums[j] + nums[l] + nums[r]
11 IF s = target THEN APPEND (nums[i], nums[j], nums[l], nums[r]) TO out
12 IF s <= target THEN l <- l + 1
13 IF s >= target THEN r <- r - 1
14 RETURN out

← / → step · space play · Home restart

Where to practice Two Pointers