3Sum Closest

MediumTwo Pointerssort + two pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums of length at least 3 and an integer target. Pick exactly three distinct indices i, j, and k and add up the three values they point to. Among all possible triples, find the one whose sum lands **closest** to target — that is, the sum that minimizes the absolute difference |sum - target|. Return that closest sum. The test data is generated so that there is exactly one such closest sum.

Examples

Input: nums = [-1, 2, 1, -4], target = 1
Output: 2
The sum that is closest to `1` is `2`, formed by `-1 + 2 + 1 = 2`.
Input: nums = [0, 0, 0], target = 1
Output: 0
The only triple sums to `0`, which differs from `1` by `1`.
Input: nums = [1, 1, 1, 0], target = -100
Output: 2
Every triple sums to either `2` or `3`; `2` is the closest reachable value to `-100`.

Constraints

  • `3 <= nums.length <= 1000`
  • `-1000 <= nums[i] <= 1000`
  • `-10^4 <= target <= 10^4`
  • Exactly one closest sum exists for the given input.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sort + two pointers problems