1600. Nearest Sum Across Lists
Two linked lists a and b each hold prices sorted in non-decreasing order. Pick one value x from a and one value y from b so that |x + y - target| is as small as possible, and return [x, y].
If several pairs give the same distance, prefer the pair with the smaller sum x + y; if that still ties, prefer the smaller x. Sums can exceed the 32-bit range, so compute them with 64-bit integers. Solve it with two pointers, one moving forward through a and one moving backward through b (reverse b first or copy it into an array), in O(n + m) time.
Example 1
- Input:
- a = [1,4,8], b = [2,5,9], target = 12
- Output:
- [4,9]
- Explanation:
4 + 9 = 13 and 8 + 5 = 13 are both one away; the sums tie, so the smaller x wins: [4, 9].
Example 2
- Input:
- a = [1,3], b = [2,4], target = 4
- Output:
- [1,2]
- Explanation:
Sums 3 and 5 are both at distance 1; the smaller sum 3 wins, giving [1, 2].
Constraints
1 ≤ length of a, length of b ≤ 105; -109 ≤ val, target ≤ 109; both lists are sorted non-decreasing.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 8,000 msC++ 2,000 msJava 4,000 msJavaScript 4,000 msTypeScript 4,000 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(n + m)