PHP Program to find the Closest Pair from Two Sorted Arrays

Given two sorted arrays and a number x, we need to find a pair (one element from each array) whose sum is closest to x. This is a classic two-pointer problem that can be solved efficiently.

Problem Statement

Find a pair from two sorted arrays such that the sum of the pair is closest to a given target value x.

Input:

ar1 = [1, 3, 5, 7, 9];
ar2 = [2, 4, 6, 8, 10];
x = 12;

Output:

The closest pair is [1, 10] because 1+10=11 which is closest to 12

Solution Using Two-Pointer Technique

We use two pointers one starting from the beginning of the first array and another from the end of the second array. We move pointers based on the current sum compared to the target ?

<?php

function findClosestPair($ar1, $ar2, $x) {
    $m = count($ar1);
    $n = count($ar2);
    
    $minDiff = PHP_INT_MAX;
    $result = array();
    
    $left = 0;
    $right = $n - 1;
    
    while ($left < $m && $right >= 0) {
        $currentSum = $ar1[$left] + $ar2[$right];
        $currentDiff = abs($currentSum - $x);
        
        // Update result if current pair is closer to x
        if ($currentDiff < $minDiff) {
            $minDiff = $currentDiff;
            $result = array($ar1[$left], $ar2[$right]);
        }
        
        // Move pointers based on comparison with target
        if ($currentSum > $x) {
            $right--;
        } else {
            $left++;
        }
    }
    
    return $result;
}

// Test the function
$ar1 = array(1, 4, 8, 10);
$ar2 = array(2, 6, 9);
$x = 20;

$closestPair = findClosestPair($ar1, $ar2, $x);
echo "The closest pair is [" . $closestPair[0] . ", " . $closestPair[1] . "]
"; echo "Sum: " . ($closestPair[0] + $closestPair[1]) . ", Target: " . $x; ?>
The closest pair is [10, 9]
Sum: 19, Target: 20

How It Works

The algorithm works by maintaining two pointers:

  • Left pointer: Starts at the beginning of the first array
  • Right pointer: Starts at the end of the second array

At each step, we calculate the sum and compare it with the target. If the sum is greater than the target, we move the right pointer left to decrease the sum. If the sum is less than the target, we move the left pointer right to increase the sum.

Time and Space Complexity

Complexity Value Explanation
Time O(m + n) Single pass through both arrays
Space O(1) Only constant extra space used

Conclusion

The two-pointer technique provides an efficient O(m + n) solution for finding the closest pair from two sorted arrays. This approach leverages the sorted nature of the arrays to systematically narrow down the search space and find the optimal pair.

Updated on: 2026-03-15T10:37:58+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements