githubEdit

28. Find the Closest Pair from Two Arrays

βœ… GFG solution to Find the Closest Pair from Two Arrays: find pair with sum closest to target using efficient two-pointer technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given two sorted arrays arr1[] and arr2[] of size n and m and a number x, find the pair whose sum is closest to x and the pair has an element from each array. In the case of multiple closest pairs, return any one of them.

Note: In the driver code, the absolute difference between the sum of the closest pair and x is printed.

πŸ“˜ Examples

Example 1

Input: arr1[] = [1, 4, 5, 7], arr2[] = [10, 20, 30, 40], x = 32
Output: [1, 30]
Explanation: The closest pair whose sum is closest to 32 is [1, 30] = 31.

Example 2

Input: arr1[] = [1, 4, 5, 7], arr2[] = [10, 20, 30, 40], x = 50
Output: [7, 40]
Explanation: The closest pair whose sum is closest to 50 is [7, 40] = 47.

Example 3

πŸ”’ Constraints

  • $1 \le \text{arr1.size()}, \text{arr2.size()} \le 10^5$

  • $1 \le \text{arr1}[i], \text{arr2}[i] \le 10^9$

  • $1 \le x \le 10^9$

βœ… My Approach

The optimal solution uses Two-Pointer Technique:

Two-Pointer Strategy

  1. Key Insight:

    • Since both arrays are sorted, we can use two pointers efficiently.

    • Start with smallest element from arr1 and largest from arr2.

    • Move pointers to bring sum closer to target x.

  2. Pointer Movement Logic:

    • If sum > x: decrease sum by moving right pointer left (arr2).

    • If sum < x: increase sum by moving left pointer right (arr1).

    • If sum == x: we found exact match, but continue to check all pairs.

  3. Tracking Best Pair:

    • Maintain minimum difference seen so far.

    • Update result whenever we find a pair with smaller difference.

    • Use abs(sum - x) to calculate difference.

  4. Algorithm Steps:

    • Initialize left pointer at start of arr1, right at end of arr2.

    • While both pointers are valid:

      • Calculate current sum and difference from x.

      • Update result if this is closer than previous best.

      • Move pointers based on comparison with x.

    • Return the closest pair found.

Why This Works: The two-pointer approach explores all potentially optimal pairs by systematically moving through both arrays based on whether we need to increase or decrease the sum.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n + m), where n and m are the sizes of the two arrays. We traverse each array at most once, with each element being visited by at most one pointer movement.

  • Expected Auxiliary Space Complexity: O(1), as we only use constant extra space for variables like pointers, difference tracking, and result storage.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Brute Force Approach

πŸ’‘ Algorithm Steps:

  1. Try all possible pairs from both arrays.

  2. For each pair, calculate sum and difference from x.

  3. Track the pair with minimum difference.

  4. Return the closest pair found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n Γ— m) - Two nested loops

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space

βœ… Why This Approach?

  • Simple and straightforward

  • No need to utilize sorted property

  • Good for small arrays

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1110/1120 test cases due to time constraints).

πŸ“Š 3️⃣ Binary Search Approach

πŸ’‘ Algorithm Steps:

  1. For each element in arr1, use binary search to find closest element in arr2.

  2. The target for binary search is (x - arr1[i]).

  3. Check both floor and ceiling values from binary search.

  4. Track the pair with minimum difference globally.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log m) - n iterations with binary search

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space

βœ… Why This Approach?

  • Utilizes sorted property of arr2

  • Better than brute force when n << m

  • Good balance of simplicity and efficiency

πŸ“Š 4️⃣ Optimized Two-Pointer with Early Exit

πŸ’‘ Algorithm Steps:

  1. Use two-pointer technique as main approach.

  2. Add early exit when exact match found (difference = 0).

  3. Track both pointers from optimal starting positions.

  4. Return immediately when perfect pair found.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n + m) - Linear with early exit

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space

βœ… Why This Approach?

  • Optimized with early exit for exact matches

  • Best average case performance

  • Maintains optimal worst case

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Two-Pointer

🟒 O(n + m)

🟒 O(1)

πŸš€ Optimal linear time

πŸ”§ Requires sorted arrays

πŸ”„ Brute Force

πŸ”΄ O(n Γ— m)

🟒 O(1)

πŸ“– Simple implementation

🐌 Quadratic time complexity

πŸ” Binary Search

🟑 O(n log m)

🟒 O(1)

🎯 Better than brute force

πŸ”§ Logarithmic factor overhead

⚑ Two-Pointer + Early Exit

🟒 O(n + m)

🟒 O(1)

⭐ Best average case

πŸ”§ Similar to main approach

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Two-Pointer

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Understanding

πŸ₯ˆ Brute Force

β˜…β˜…β˜…β˜†β˜†

🎯 Unbalanced array sizes

πŸ₯‰ Binary Search

β˜…β˜…β˜…β˜…β˜†

⚑ Many exact matches expected

πŸ… Two-Pointer + Early Exit

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated