Closest Pair in Two Arrays
Detailed guide and Python implementation for the 'Closest Pair in Two Arrays' problem.
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 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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Try/Except & Error Handling
Prevent your Python scripts from crashing. Learn try, except, finally blocks and how to raise custom exceptions properly.
How to Reverse a String in Python
Learn how to reverse a string in Python using slicing, the reversed() function, and loop concatenation with visual code examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.