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
function countPairs ( arr1 , arr2 , m , n , x ) { let count = 0 ; let l = 0 , r = n - 1 ; while ( l < m && r >= 0 ) { if ( ( arr1 [ l ] + arr2 [ r ] ) == x ) { l ++ ; r -- ; count ++ ; } else if ( ( arr1 [ l ] + arr2 [ r ] ) < x ) l ++ ; else r -- ; } return count ; } let arr1 = [ 1 , 3 , 5 , 7 ] ; let arr2 = [ 2 , 3 , 5 , 8 ] ; let m = arr1 . length ; let n = arr2 . length ; let x = 10 ; document . write ( " " + countPairs ( arr1 , arr2 , m , n , x ) ) ;