3Sum Closest

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: 3Sum Closest

Approach

Sort the array, then fix one element with an outer loop and use two converging pointers for the remaining pair. Track the sum closest to the target by comparing absolute differences. Adjust pointers based on whether the current sum is less than or greater than the target.

Complexity Analysis

Time
O(n^2)
Space
O(1)

Pattern

Two Pointers (Converging) + Sort

Why It Works

Sorting allows the two-pointer approach to systematically explore sums: moving left increases the sum, moving right decreases it, efficiently narrowing in on the closest possible sum.

Updated Feb 2026