3Sum
Problem Statement
You are given an integer array nums.
Find every triplet of values [nums[i], nums[j], nums[k]], taken from three different positions, whose sum is 0.
Each triplet may appear only once in the answer. Two triplets count as the same if they hold the same three values, even if they came from different positions. The order of the triplets, and of the values inside them, does not matter.
An integer array nums.
A list of all unique triplets (as lists of 3 values) that add up to 0.
−1 + 0 + 1 = 0 can be made with either of the two −1s, but it is listed only once. −1 + −1 + 2 = 0 uses both −1s.
The only triplet is 0 + 1 + 1 = 2.
The only triplet adds up to 0.
- • 3 ≤ nums.length ≤ 3000
- • −10^5 ≤ nums[i] ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Three loops; store each zero-sum triplet sorted in a set
Fix nums[i]; for each j, look up the needed third value in a set
Sort; fix nums[i]; two pointers; skip equal values at every level
Try every i < j < k. When the three values add up to 0, sort those three values and put them in a set. The set throws away repeats, because the same three values always sort to the same list.
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.