3Sum Closest
Problem Statement
You are given an integer array nums and a number target.
Pick three elements from three different positions. Among all such triplets, find the one whose sum is closest to target, and return that sum.
You may assume there is exactly one closest sum.
An integer array nums and an integer target.
One integer: the triplet sum with the smallest |sum − target|.
−1 + 2 + 1 = 2 is only 1 away from the target. No triplet sums to exactly 1.
The only triplet adds up to 0.
- • 3 ≤ nums.length ≤ 500
- • −1000 ≤ nums[i] ≤ 1000
- • −10^4 ≤ target ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Three loops; keep the sum with the smallest distance
Sort; for each pair, binary search the value closest to what's left
Sort; fix nums[i]; move left/right towards the target, track the closest
Check every triplet i < j < k. Keep the sum whose distance |sum − target| is smallest.
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.