Find the closest pair from two sorted arrays | Python3 program to find the pair from two sorted arays such that the sum of pair is closest to a given number x ; ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays and x is given number . This function prints the pair from both arrays such that the sum of the pair is closest to x . ; Initialize the diff between pair sum and x . ; Start from left side of ar1 [ ] and right side of ar2 [ ] ; If this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; If sum of this pair is more than x , move to smaller side ; move to the greater side ; Print the result ; Driver program to test above functions
import sys NEW_LINE def printClosest ( ar1 , ar2 , m , n , x ) : NEW_LINE INDENT diff = sys . maxsize NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l < m and r >= 0 ) : NEW_LINE INDENT if abs ( ar1 [ l ] + ar2 [ r ] - x ) < diff : NEW_LINE INDENT res_l = l NEW_LINE res_r = r NEW_LINE diff = abs ( ar1 [ l ] + ar2 [ r ] - x ) NEW_LINE DEDENT if ar1 [ l ] + ar2 [ r ] > x : NEW_LINE INDENT r = r - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = l + 1 NEW_LINE DEDENT DEDENT print ( " The ▁ closest ▁ pair ▁ is ▁ [ " , ar1 [ res_l ] , " , " , ar2 [ res_r ] , " ] " ) NEW_LINE DEDENT ar1 = [ 1 , 4 , 5 , 7 ] NEW_LINE ar2 = [ 10 , 20 , 30 , 40 ] NEW_LINE m = len ( ar1 ) NEW_LINE n = len ( ar2 ) NEW_LINE x = 38 NEW_LINE printClosest ( ar1 , ar2 , m , n , x ) NEW_LINE