![]() |
VOOZH | about |
Given two sorted arrays a[] and b[] consisting of distinct elements and a value x. Count all pairs from both arrays whose sum is equal to x.
Note: The pair has an element from each array.
Examples :
Input: a[] = [1, 3, 5, 7], b[] = [2, 3, 5, 8], x = 10
Output: 2
Explanation: The pairs are: (5, 5) and (7, 3)Input: a[] = [1, 2, 3, 4, 5, 7, 11] , b[] = [2, 3, 4, 5, 6, 8, 12], x = 9
Output: 5
Explanation: The pairs are: (1, 8), (3, 6), (4, 5), (5, 4) and (7, 2)
Table of Content
The idea is to use two loops to pick elements one by one on both the arrays and check whether the sum of the elements is equal to x or not.
2
We traverse one of the arrays and search the corresponding element (such that their sum is x) in other array using binary search. Let's say the current element in one of the arrays is p, then we search for (x-p) element in other array using binary search. Binary search is valid as both of the arrays are sorted.
Output :
2Time Complexity : O(m*log(n)), searching should be applied on the array which is of greater size so as to reduce the time complexity.
Auxiliary space : O(1)
We store all elements of first array in hash table. For elements of second array, we subtract every element from x and check the result in hash table. If result is present, we increment the count.
Output :
2Time Complexity : O(m + n)
Auxiliary space : O(m), hash table should be created of the array having smaller size so as to reduce the space complexity
The main idea is to use the concept of two pointers, one to traverse 1st array from left to right and another to traverse the 2nd array from right to left.
There are 3 possible cases for moving the pointers:
Case 1: If the sum of elements at the pointers = x, then move the pointers and increment the count.
Case 2: If the sum of elements < x, then move the left pointer to point to greater element (present on right).
Case 3: If the sum of elements > x, then move the right pointer to point to smaller element (present on left).
Output :
2