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
[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.
#include <iostream>
#include <vector>
using namespace std;
int countPairs(vector<int>& a, vector<int>& b, int x) {
int m = a.size();
int n = b.size();
int count = 0;
// checking for all pairs from both the arrays
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// if sum of pair is equal to 'x' increment count
if ((a[i] + b[j]) == x)
count++;
}
}
return count;
}
int main() {
vector<int> a = {1, 3, 5, 7};
vector<int> b = {2, 3, 5, 8};
int x = 10;
cout << countPairs(a, b, x);
return 0;
}
class GFG {
static int countPairs(int[] a, int[] b, int x) {
int m = a.length;
int n = b.length;
int count = 0;
// checking for all pairs from both the arrays
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// if sum of pair is equal to 'x' increment count
if ((a[i] + b[j]) == x)
count++;
}
}
return count;
}
public static void main (String[] args) {
int[] a = {1, 3, 5, 7};
int[] b = {2, 3, 5, 8};
int x = 10;
System.out.println(countPairs(a, b, x));
}
}
def countPairs(a, b, x):
m = len(a)
n = len(b)
count = 0
# checking for all pairs from both the arrays
for i in range(m):
for j in range(n):
# if sum of pair is equal to 'x' increment count
if a[i] + b[j] == x:
count = count + 1
return count
if __name__ == '__main__':
a = [1, 3, 5, 7]
b = [2, 3, 5, 8]
x = 10
print(countPairs(a, b, x))
using System;
class GFG {
static int countPairs(int[] a, int[] b, int x) {
int m = a.Length;
int n = b.Length;
int count = 0;
// checking for all pairs from both the arrays
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// if sum of pair is equal to 'x' increment count
if ((a[i] + b[j]) == x)
count++;
}
}
return count;
}
public static void Main () {
int[] a = {1, 3, 5, 7};
int[] b = {2, 3, 5, 8};
int x = 10;
Console.WriteLine(countPairs(a, b, x));
}
}
function countPairs(a, b, x) {
let m = a.length;
let n = b.length;
let count = 0;
// checking for all pairs from both the arrays
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
// if sum of pair is equal to 'x' increment count
if ((a[i] + b[j]) == x)
count++;
}
}
return count;
}
// Driver Code
let a = [1, 3, 5, 7];
let b = [2, 3, 5, 8];
let x = 10;
console.log(countPairs(a, b, x));
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.
#include <iostream>
#include <vector>
using namespace std;
// function to search value using binary search
bool isPresent(vector<int>& arr, int low, int high, int value) {
while (low <= high) {
int mid = (low + high) / 2;
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
int countPairs(vector<int>& a, vector<int>& b, int x) {
int m = a.size();
int n = b.size();
int count = 0;
for (int i = 0; i < m; i++) {
int value = x - a[i];
// check if value is present in the array
if (isPresent(b, 0, n - 1, value))
count++;
}
return count;
}
int main() {
vector<int> a = {1, 3, 5, 7};
vector<int> b = {2, 3, 5, 8};
int x = 10;
cout << countPairs(a, b, x);
return 0;
}
class GFG {
// function to search value using binary search
static boolean isPresent(int arr[], int low, int high, int value) {
while (low <= high) {
int mid = (low + high) / 2;
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
static int countPairs(int a[], int b[], int x) {
int m = a.length;
int n = b.length;
int count = 0;
for (int i = 0; i < m; i++) {
int value = x - a[i];
// check if value is present in the array
if (isPresent(b, 0, n - 1, value))
count++;
}
return count;
}
public static void main (String[] args) {
int a[] = {1, 3, 5, 7};
int b[] = {2, 3, 5, 8};
int x = 10;
System.out.println(countPairs(a, b, x));
}
}
# function to search value using binary search
def isPresent(arr, low, high, value):
while (low <= high):
mid = (low + high) // 2
# value found
if (arr[mid] == value):
return True
elif (arr[mid] > value) :
high = mid - 1
else:
low = mid + 1
# value not found
return False
def countPairs(a, b, x):
count = 0
m = len(a)
n = len(b)
for i in range(m):
value = x - a[i]
# check if value is present in the array
if (isPresent(b, 0, n - 1, value)):
count += 1
return count
if __name__ == "__main__":
a = [1, 3, 5, 7]
b = [2, 3, 5, 8]
x = 10
print(countPairs(a, b, x))
using System;
class GFG {
// function to search value using binary search
static bool isPresent(int []arr, int low, int high, int value) {
while (low <= high) {
int mid = (low + high) / 2;
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
static int countPairs(int []a, int []b, int x) {
int m = a.Length;
int n = b.Length;
int count = 0;
for (int i = 0; i < m; i++) {
// for each arr1[i]
int value = x - a[i];
// check if value is present in the array
if (isPresent(b, 0, n - 1, value))
count++;
}
return count;
}
public static void Main () {
int []a = {1, 3, 5, 7};
int []b = {2, 3, 5, 8};
int x = 10;
Console.WriteLine(countPairs(a, b, x));
}
}
// function to search value using binary search
function isPresent(arr, low, high, value) {
while (low <= high) {
let mid = Math.floor((low + high) / 2);
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
function countPairs(a, b, x) {
let m = a.length;
let n = b.length;
let count = 0;
for (let i = 0; i < m; i++) {
let value = x - a[i];
// check if value is present in the array
if (isPresent(b, 0, n - 1, value))
count++;
}
return count;
}
// Driver Code
let a =[1, 3, 5, 7];
let b =[2, 3, 5, 8];
let x = 10;
console.log(countPairs(a, b, x));
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)
[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.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int countPairs(vector<int>& a, vector<int>& b, int x) {
int count = 0;
int m = a.size();
int n = b.size();
unordered_set<int> st;
// insert all the elements in the hashtable
for (int i = 0; i < m; i++)
st.insert(a[i]);
// for each element of b
for (int j = 0; j < n; j++) {
if (st.find(x - b[j]) != st.end())
count++;
}
return count;
}
int main() {
vector<int> a = {1, 3, 5, 7};
vector<int> b = {2, 3, 5, 8};
int x = 10;
cout << countPairs(a, b, x);
return 0;
}
import java.util.HashSet;
class GFG
{
static int countPairs(int a[], int b[], int x) {
int m = a.length;
int n = b.length;
int count = 0;
HashSet<Integer> set = new HashSet<Integer>();
// insert all the elements in the hashtable
for (int i = 0; i < m; i++)
set.add(a[i]);
// for each element of b
for (int j = 0; j < n; j++) {
if (set.contains(x - b[j]))
count++;
}
return count;
}
public static void main(String[] args) {
int a[] = {1, 3, 5, 7};
int b[] = {2, 3, 5, 8};
int x = 10;
System.out.print(countPairs(a, b, x));
}
}
def countPairs(a, b, x):
m = len(a)
n = len(b)
count = 0
st = set()
# insert all the elements in the hashtable
for i in range(m):
st.add(a[i])
# for each element of b
for j in range(n):
if x - b[j] in st:
count += 1
return count
if __name__ == '__main__':
a = [1, 3, 5, 7]
b = [2, 3, 5, 8]
x = 10
print(countPairs(a, b, x))
using System;
using System.Collections.Generic;
class GFG
{
static int countPairs(int []a, int []b, int x) {
int m = a.Length;
int n = b.Length;
int count = 0;
HashSet<int> set = new HashSet<int>();
// insert all the elements in the hashtable
for (int i = 0; i < m; i++)
set.Add(a[i]);
// for each element of b
for (int j = 0; j < n; j++) {
if(set.Contains(x - b[j]))
count++;
}
return count;
}
public static void Main(String[] args) {
int []a = {1, 3, 5, 7};
int []b = {2, 3, 5, 8};
int x = 10;
Console.Write(countPairs(a, b, x));
}
}
function countPairs(a, b, x) {
let m = a.length;
let n = b.length;
let count = 0;
let st = new Set();
// insert all the elements in the hashtable
for (let i = 0; i < m; i++)
st.add(a[i]);
// for each element of b
for (let j = 0; j < n; j++) {
if (st.has(x - b[j]))
count++;
}
return count;
}
// Driver Code
let a = [1, 3, 5, 7];
let b = [2, 3, 5, 8];
let x = 10;
console.log(countPairs(a, b, x));
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
[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).
#include <iostream>
#include <vector>
using namespace std;
int countPairs(vector<int>& a, vector<int>& b , int x) {
int count = 0;
int m = a.size();
int n = b.size();
int l = 0, r = n - 1;
// traverse a[] from left to right, and traverse b[] from right to left
while (l < m && r >= 0) {
if ((a[l] + b[r]) == x) {
l++; r--;
count++;
}
else if ((a[l] + b[r]) < x)
l++;
else
r--;
}
return count;
}
int main() {
vector<int> a = {1, 3, 5, 7};
vector<int> b = {2, 3, 5, 8};
int x = 10;
cout << countPairs(a, b, x);
return 0;
}
class GFG {
static int countPairs(int a[], int b[], int x) {
int m = a.length;
int n = b.length;
int count = 0;
int l = 0, r = n - 1;
// traverse a[] from left to right, and traverse b[] from right to left
while (l < m && r >= 0) {
if ((a[l] + b[r]) == x) {
l++; r--;
count++;
}
else if ((a[l] + b[r]) < x)
l++;
else
r--;
}
return count;
}
public static void main (String[] args) {
int a[] = {1, 3, 5, 7};
int b[] = {2, 3, 5, 8};
int x = 10;
System.out.println(countPairs(a, b, x));
}
}
def countPairs(a, b, x):
m = len(a)
n = len(b)
count, l, r = 0, 0, n - 1
# traverse a[] from left to right, and traverse b[] from right to left
while (l < m and r >= 0):
if ((a[l] + b[r]) == x):
l += 1
r -= 1
count += 1
elif ((a[l] + b[r]) < x):
l += 1
else:
r -= 1
return count
if __name__ == '__main__':
a = [1, 3, 5, 7]
b = [2, 3, 5, 8]
x = 10
print(countPairs(a, b, x))
using System;
class GFG {
static int countPairs(int []a, int []b, int x) {
int m = a.Length;
int n = b.Length;
int count = 0;
int l = 0, r = n - 1;
// traverse a[] from left to right, and traverse b[] from right to left
while (l < m && r >= 0) {
if ((a[l] + b[r]) == x) {
l++; r--;
count++;
}
else if ((a[l] + b[r]) < x)
l++;
else
r--;
}
return count;
}
public static void Main () {
int[] a = {1, 3, 5, 7};
int[] b = {2, 3, 5, 8};
int x = 10;
Console.WriteLine(countPairs(a, b, x));
}
}
function countPairs(a, b, x) {
let m = a.length;
let n = b.length;
let count = 0;
let l = 0, r = n - 1;
// traverse a[] from left to right, and traverse b[] from right to left
while (l < m && r >= 0) {
if ((a[l] + b[r]) == x) {
l++; r--;
count++;
}
else if ((a[l] + b[r]) < x)
l++;
else
r--;
}
return count;
}
// Driver Code
let a = [1, 3, 5, 7];
let b = [2, 3, 5, 8];
let x = 10;
console.log(countPairs(a, b, x));
Output :
2