Skip to content

visual walkthrough

3Sum Closest

MediumSort + Two PointersReported at: MetaAmazonGoogle+4

Same skeleton as 3Sum but optimising a distance instead of matching.

Solve on LeetCode

The idea

Same trick as 3Sum: sort, fix one number, and walk two pointers inward. Instead of looking for exactly zero, remember the sum that has been closest to the target.

If the sum is too small move the left pointer up; too big, move the right pointer down.

Complexity

approachtimespace
Three loopsO(n³)O(1)
Sort + two pointersO(n²)O(1)

More walkthroughs