Closest Pair in Two Arrays
Detailed guide and Python implementation for the 'Closest Pair in Two Arrays' problem.
1. Concept Overview
The 'Closest Pair in Two Arrays' problem is a key challenge in the Searching & Sorting section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Closest Pair in Two Arrays.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Closest Pair in Two Arrays carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
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.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def closest_pair_two_arrays_opt(arr1, arr2, x):
arr1.sort(); arr2.sort()
l, r = 0, len(arr2) - 1
min_diff = float('inf'); res = (0, 0)
while l < len(arr1) and r >= 0:
if abs(arr1[l] + arr2[r] - x) < min_diff:
min_diff = abs(arr1[l] + arr2[r] - x); res = (arr1[l], arr2[r])
if arr1[l] + arr2[r] > x: r -= 1
else: l += 1
return resBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def closest_pair_two_arrays_brute(arr1, arr2, x):
min_diff = float('inf'); res = (0, 0)
for i in range(len(arr1)):
for j in range(len(arr2)):
if abs(arr1[i] + arr2[j] - x) < min_diff:
min_diff = abs(arr1[i] + arr2[j] - x); res = (arr1[i], arr2[j])
return resAlgorithm Pattern Checklist
When dealing with Searching & Sorting data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
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.