Count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if this sum is equal to ' x ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if this sum is less than x , then increment l ; else decrement ' r ' ; required count of pairs ; Driver Code
< ? php function countPairs ( $ arr1 , $ arr2 , $ m , $ n , $ x ) { $ count = 0 ; $ l = 0 ; $ r = $ n - 1 ; while ( $ l < $ m and $ r >= 0 ) { if ( ( $ arr1 [ $ l ] + $ arr2 [ $ r ] ) == $ x ) { $ l ++ ; $ r -- ; $ count ++ ; } else if ( ( $ arr1 [ $ l ] + $ arr2 [ $ r ] ) < $ x ) $ l ++ ; else $ r -- ; } return $ count ; } $ arr1 = array ( 1 , 3 , 5 , 7 ) ; $ arr2 = array ( 2 , 3 , 5 , 8 ) ; $ m = count ( $ arr1 ) ; $ n = count ( $ arr2 ) ; $ x = 10 ; echo " Count ▁ = ▁ " , countPairs ( $ arr1 , $ arr2 , $ m , $ n , $ x ) ; ? >