4Sum
Problem Statement
You are given an integer array nums and a number target.
Find every group of four values, taken from four different positions, whose sum is exactly target.
Each group may appear only once: two groups with the same four values count as the same, even if they came from different positions. The order of the groups, and of the values inside them, does not matter.
An integer array nums and an integer target.
A list of all unique quadruplets (lists of 4 values) that add up to target.
These are the only three different groups of values that add up to 0. Some can be built from different positions (there are two 0s), but each is listed once.
Many position-groups give 2 + 2 + 2 + 2, but it is one answer.
- • 1 ≤ nums.length ≤ 200
- • −10^9 ≤ nums[i] ≤ 10^9
- • −10^9 ≤ target ≤ 10^9
- • A sum of four values can reach ±4·10^9, which does not fit in an `int`.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Four loops; store each matching group sorted in a set
Fix a, b; for each c, look up the needed fourth value in a set
Sort; fix a and b (skipping repeats); two pointers for the last pair
Try every a < b < c < d. When the four values add up to target, sort them and put them in a set, which drops repeats.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.