visual walkthrough
3Sum Closest
Same skeleton as 3Sum but optimising a distance instead of matching.
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
| approach | time | space |
|---|---|---|
| Three loops | O(n³) | O(1) |
| Sort + two pointers | O(n²) | O(1) |