VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-two-sorted-arrays-whose-sum-equal-given-value-x/

⇱ Count Pair Sum Equals Target - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Pair Sum Equals Target

Last Updated : 25 Sep, 2025

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)

[Naive Approach] Two loops to check for all possible pairs - O(n^2) Time and O(1) Space

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.


Output
2

[Better Approach - 1] Using Binary Search

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 :

2

Time 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)

[Better Approach - 2] Using Hashing

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 :

2

Time 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

[Expected Approach] Using Two Pointers - O(m + n) Time and O(1) Space

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
Comment
Article Tags: