Problem 356830 · easy · Phase 03 Linear Management & Searching

Pair Sum Closest to a Target

two pointers · sorted arrays

Given a list of integers nums sorted in non-decreasing order (at least two elements) and an integer target, return the sum of two distinct-index elements that is closest to target. If two different sums are equally close, return the smaller sum.

Examples

Input:  nums = [1, 3, 4, 7, 10], target = 15
Output: 14
Explanation: 4 + 10 = 14 is one away from 15; no pair is closer.

Input:  nums = [1, 5, 7, 9], target = 9
Output: 8
Explanation: 1 + 7 = 8 and 1 + 9 = 10 are both one away; the smaller sum wins.

Constraints

  • 2 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space.

Goals

  • Move the correct pointer based on whether the sum is too small or too large
  • Track the best candidate with a tie-break rule
Starting Python…