Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | Function to check if the array has 2 elements whose sum is equal to the given value ; Sort the array in increasing order ; Traverse the array , nums [ ] ; Store the required number to be found ; Perform binary search ; Store the mid value ; If nums [ mid ] is greater than x , then update high to mid - 1 ; If nums [ mid ] is less than x , then update low to mid + 1 ; Otherwise ; If mid is equal i , check mid - 1 and mid + 1 ; Otherwise , prthe pair and return ; If no such pair is found , then pr - 1 ; Driver Code ; Function Call
def hasArrayTwoPairs ( nums , n , target ) : NEW_LINE INDENT nums = sorted ( nums ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = target - nums [ i ] NEW_LINE low , high = 0 , n - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( ( high - low ) // 2 ) NEW_LINE if ( nums [ mid ] > x ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT elif ( nums [ mid ] < x ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( mid == i ) : NEW_LINE INDENT if ( ( mid - 1 >= 0 ) and nums [ mid - 1 ] == x ) : NEW_LINE INDENT print ( nums [ i ] , end = " , ▁ " ) NEW_LINE print ( nums [ mid - 1 ] ) NEW_LINE return NEW_LINE DEDENT if ( ( mid + 1 < n ) and nums [ mid + 1 ] == x ) : NEW_LINE INDENT print ( nums [ i ] , end = " , ▁ " ) NEW_LINE print ( nums [ mid + 1 ] ) NEW_LINE return NEW_LINE DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT print ( nums [ i ] , end = " , ▁ " ) NEW_LINE print ( nums [ mid ] ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 0 , - 1 , 2 , - 3 , 1 ] NEW_LINE X = - 2 NEW_LINE N = len ( A ) NEW_LINE hasArrayTwoPairs ( A , N , X ) NEW_LINE DEDENT