Competitive ProgrammingEasy

Closest Pair in Two Arrays

Detailed guide and Python implementation for the 'Closest Pair in Two Arrays' problem.

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?
Consider using Searching & Sorting-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.