1277. Closest Cross Pair
Two weather stations each log daily temperatures, and each log is sorted in non-decreasing order. A researcher wants to find the pair of readings, one taken from a and one taken from b, that are as close together as possible.
Return the smallest value of |a[i] - b[j]| over all choices of an index i in a and an index j in b. Both arrays hold at least one value. Do not compare every pair: keep one pointer in each array and always advance the pointer that sits on the smaller value, because moving the larger one can only widen the gap. Aim for O(a.length + b.length) time and O(1) extra space.
Example 1
- Input:
- a = [1,4,9], b = [2,3,10]
- Output:
- 1
- Explanation:
The pairs (1, 2), (4, 3) and (9, 10) are each 1 apart, and no pair is closer than 1.
Example 2
- Input:
- a = [5], b = [5]
- Output:
- 0
- Explanation:
Both logs hold the same reading, so the gap is 0.
Constraints
1 ≤ a.length, b.length ≤ 1000
0 ≤ a[i], b[j] ≤ 109
a and b are each sorted in non-decreasing order
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n + m)
- Space
- O(1)