FunctionRacerProblemsRace

Closest Pair Sum in a Sorted List

EasyTwo pointersPython, JavaScript, TypeScript, Java, C++

nums is sorted in non-decreasing order and has at least two items. Choose two items from different positions so that their sum is as close as possible to target, and return that sum.

If two different sums are equally close to target (one below it and one above it), return the smaller sum. One index starting at each end and moving inward finds the answer in a single pass: a sum below the target can only improve by moving the left index up, a sum above it by moving the right index down.

Example 1

nums [1,2,4,7,11]
target 9
returns 9

2 + 7 = 9 hits the target exactly.

Example 2

nums [1,3,5,8]
target 10
returns 9

The sums 9 (1 + 8) and 11 (3 + 8) are both 1 away from 10; the smaller one wins.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Two pointers problems