Back to Practice Dashboard
Competitive ProgrammingEasy

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

Easy

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.

Constraints
  • 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

Example 1
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 32)
Output
(1, 30)
Explanation

1 from arr1 and 30 from arr2 sum to 31, which is closest to 32 (absolute difference is 1).

Example 2
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 50)
Output
(7, 40)
Explanation

7 from arr1 and 40 from arr2 sum to 47, which is closest to 50 (absolute difference is 3).

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
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.

Open in Editor