Count pairs from two sorted arrays whose sum is equal to a given value x | C ++ implementation to count pairs from both sorted arrays whose sum is equal to a given value ; function to search ' value ' in the given array ' arr [ ] ' it uses binary search technique as ' arr [ ] ' is sorted ; value found ; value not found ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; for each arr1 [ i ] ; check if the ' value ' is present in ' arr2 [ ] ' ; required count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPresent ( int arr [ ] , int low , int high , int value ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] == value ) return true ; else if ( arr [ mid ] > value ) high = mid - 1 ; else low = mid + 1 ; } return false ; } int countPairs ( int arr1 [ ] , int arr2 [ ] , int m , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int value = x - arr1 [ i ] ; if ( isPresent ( arr2 , 0 , n - 1 , value ) ) count ++ ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 2 , 3 , 5 , 8 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int x = 10 ; cout << " Count ▁ = ▁ " << countPairs ( arr1 , arr2 , m , n , x ) ; return 0 ; }