As reported: Microsoft SDE-1 L60 (Windows team, Noida, Feb 2025), first round: the standard two-sum, modified to return the pair whose sum is closest to the target. Questions on fundamentals followed whenever a newer C++ feature or data structure was used.
Given an integer array nums (at least two elements) and an integer target, pick two elements at different indices whose sum is closest to target. Return their values as [smaller, larger].
Example 1
nums = [10,22,28,29,30,40], target = 54 -> [22,30]
22 + 30 = 52 is 2 away; no pair is closer.
Example 2
nums = [1,3,4,7,10], target = 15 -> [4,10]
Example 3
nums = [-1,2,1,-4], target = 1 -> [-1,2]
An exact match is the closest possible.
Clarifications
- If several pairs are equally close, return the one with the smaller sum; if they also have the same sum, the one with the smaller first value.
- The same value may be used twice only if it appears twice in
nums.
Constraints: 2 ≤ nums.length ≤ 5 · 10^4; -10^9 ≤ nums[i], target ≤ 10^9 (sums need 64 bits).
Code runner format: one JSON value per line: nums, target. Implement closestPair(nums, target); the harness prints the result.