Closest Pair in Two Arrays
Learn how to solve the 'Closest Pair in Two Arrays' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function closest_pair_two_arrays(arr1, arr2, x) that takes two sorted arrays of integers arr1 and arr2, and a target integer x. It should find and return a tuple (a, b) where a is from arr1 and b is from arr2 such that the absolute difference between (a + b) and x is minimized. If there are multiple such pairs, return the one with the smallest element from arr1.
- •1 <= len(arr1), len(arr2) <= 10^5
- •arr1 and arr2 are sorted in ascending order.
- •-10^9 <= arr1[i], arr2[j], x <= 10^9
Examples
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 32)
(1, 30)
1 from arr1 and 30 from arr2 sum to 31, which is closest to 32 (absolute difference is 1).
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 50)
(7, 40)
7 from arr1 and 40 from arr2 sum to 47, which is closest to 50 (absolute difference is 3).
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.