Count of equal value pairs from given two Arrays such that a[i] equals b[j]
Last Updated :
23 Jul, 2025
Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j].
Examples:
Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}
Output: 11
Explanation: Following are the 11 pairs with given condition The 11 pairs are {{1, 1}, {1, 1}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {3, 3}, {5, 5}, {5, 5}, {5, 5}} .
Input: a[] = {1, 2, 3, 4}, b[] = {1, 1, 2}
Output: 3
Approach: This problem can be solved by using the Two Pointer approach. Let i point to the first element of array a[] and j point to the first element of array b[]. While traversing the arrays, there will be 3 cases.
Case 1: a[i] = b[j] Let target denote arr[i], cnt1 denote number of elements of array a that are equal to target and cnt2 denote the number of elements of array b that are equal to target. So the total number of pairs such that a[i] = b[j] is cnt1 * cnt2 . So our answer is incremented by cnt1 * cnt2 .
Case 2: a[i] < b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing i, so we do i++.
Case 3: a[i] > b[j] The only possibility of getting a[i] = b[j] in the future is by incrementing j, so we do j++ .
Follow the steps below to solve the given problem.
- Initialize the variables ans, i and j as 0.
- Initialize answer, i, and j to 0 and start traversing both of the arrays till i is less than N or j is less than M.
- If a[i] equals b[j], calculate cnt1 and cnt2 and increment the answer by cnt1 * cnt2.
- If a[i] is less than b[j], increment i.
- If a[i] is greater than b[j], increment j.
- After performing the above steps, print the values of ans as the answer.
Below is the implementation of the above approach:
C++
// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find number of pairs with
// satisfying the given condition
int findPairs(int* a, int* b, int n, int m)
{
// Initialize ans, i, j to 0 .
int ans = 0, i = 0, j = 0;
// Use the two pointer approach to
// calculate the answer .
while (i < n && j < m) {
// Case - 1
if (a[i] == b[j]) {
// Target denotes a[i]
// or b[j] as a[i] = b[j].
// cnt1 denotes the number
// of elements in array
// a that are equal to target.
// cnt2 denotes the number
// of elements in array
// b that are equal to target
int target = a[i], cnt1 = 0, cnt2 = 0;
// Calculate cnt1
while (i < n && a[i] == target) {
cnt1++;
i++;
}
// Calculate cnt2
while (j < m && b[j] == target) {
cnt2++;
j++;
}
// Increment the answer by (cnt1 * cnt2)
ans += (cnt1 * cnt2);
}
// Case - 2
else if (a[i] < b[j])
i++;
// Case - 3
else
j++;
}
// Return the answer
return ans;
}
// Driver Code
int main()
{
int N = 8, M = 7;
int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 };
int b[] = { 1, 3, 3, 4, 5, 5, 5 };
cout << findPairs(a, b, N, M);
}
Java
// Java program for above approach
import java.io.*;
class GFG{
// Function to find number of pairs with
// satisfying the given condition
static int findPairs(int[] a, int[] b, int n, int m)
{
// Initialize ans, i, j to 0 .
int ans = 0, i = 0, j = 0;
// Use the two pointer approach to
// calculate the answer .
while (i < n && j < m)
{
// Case - 1
if (a[i] == b[j])
{
// Target denotes a[i]
// or b[j] as a[i] = b[j].
// cnt1 denotes the number
// of elements in array
// a that are equal to target.
// cnt2 denotes the number
// of elements in array
// b that are equal to target
int target = a[i], cnt1 = 0, cnt2 = 0;
// Calculate cnt1
while (i < n && a[i] == target)
{
cnt1++;
i++;
}
// Calculate cnt2
while (j < m && b[j] == target)
{
cnt2++;
j++;
}
// Increment the answer by (cnt1 * cnt2)
ans += (cnt1 * cnt2);
}
// Case - 2
else if (a[i] < b[j])
i++;
// Case - 3
else
j++;
}
// Return the answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 8, M = 7;
int a[] = { 1, 1, 3, 3, 3, 5, 8, 8 };
int b[] = { 1, 3, 3, 4, 5, 5, 5 };
System.out.println(findPairs(a, b, N, M));
}
}
// This code is contributed by Potta Lokesh
Python
# Python3 program for above approach
# Function to find number of pairs with
# satisfying the given condition
def findPairs(a, b, n, m):
# Initialize ans, i, j to 0 .
ans = 0
i = 0
j = 0
# Use the two pointer approach to
# calculate the answer .
while (i < n and j < m):
# Case - 1
if (a[i] == b[j]):
# Target denotes a[i]
# or b[j] as a[i] = b[j].
# cnt1 denotes the number
# of elements in array
# a that are equal to target.
# cnt2 denotes the number
# of elements in array
# b that are equal to target
target = a[i]
cnt1 = 0
cnt2 = 0
# Calculate cnt1
while (i < n and a[i] == target):
cnt1 += 1
i += 1
# Calculate cnt2
while (j < m and b[j] == target):
cnt2 += 1
j += 1
# Increment the answer by (cnt1 * cnt2)
ans += (cnt1 * cnt2)
# Case - 2
elif (a[i] < b[j]):
i += 1
# Case- 3
else:
j += 1
# Return the answer
return ans
# Driver Code
if __name__ == "__main__":
N = 8
M = 7
a = [ 1, 1, 3, 3, 3, 5, 8, 8 ]
b = [ 1, 3, 3, 4, 5, 5, 5 ]
print(findPairs(a, b, N, M))
# This code is contributed by ukasp
C#
// C# program for above approach
using System;
class GFG{
// Function to find number of pairs with
// satisfying the given condition
static int findPairs(int[] a, int[] b, int n, int m)
{
// Initialize ans, i, j to 0 .
int ans = 0, i = 0, j = 0;
// Use the two pointer approach to
// calculate the answer .
while (i < n && j < m)
{
// Case - 1
if (a[i] == b[j])
{
// Target denotes a[i]
// or b[j] as a[i] = b[j].
// cnt1 denotes the number
// of elements in array
// a that are equal to target.
// cnt2 denotes the number
// of elements in array
// b that are equal to target
int target = a[i], cnt1 = 0, cnt2 = 0;
// Calculate cnt1
while (i < n && a[i] == target)
{
cnt1++;
i++;
}
// Calculate cnt2
while (j < m && b[j] == target)
{
cnt2++;
j++;
}
// Increment the answer by (cnt1 * cnt2)
ans += (cnt1 * cnt2);
}
// Case - 2
else if (a[i] < b[j])
i++;
// Case - 3
else
j++;
}
// Return the answer
return ans;
}
// Driver Code
public static void Main()
{
int N = 8, M = 7;
int []a = { 1, 1, 3, 3, 3, 5, 8, 8 };
int []b = { 1, 3, 3, 4, 5, 5, 5 };
Console.Write(findPairs(a, b, N, M));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// Javascript Program for above approach
// Function to find number of pairs with
// satisfying the given condition
function findPairs(a, b, n, m)
{
// Initialize ans, i, j to 0 .
let ans = 0, i = 0, j = 0;
// Use the two pointer approach to
// calculate the answer .
while (i < n && j < m) {
// Case - 1
if (a[i] == b[j]) {
// Target denotes a[i]
// or b[j] as a[i] = b[j].
// cnt1 denotes the number
// of elements in array
// a that are equal to target.
// cnt2 denotes the number
// of elements in array
// b that are equal to target
let target = a[i], cnt1 = 0, cnt2 = 0;
// Calculate cnt1
while (i < n && a[i] == target) {
cnt1++;
i++;
}
// Calculate cnt2
while (j < m && b[j] == target) {
cnt2++;
j++;
}
// Increment the answer by (cnt1 * cnt2)
ans += (cnt1 * cnt2);
}
// Case - 2
else if (a[i] < b[j])
i++;
// Case - 3
else
j++;
}
// Return the answer
return ans;
}
// Driver Code
let N = 8, M = 7;
let a = [ 1, 1, 3, 3, 3, 5, 8, 8 ];
let b = [ 1, 3, 3, 4, 5, 5, 5 ];
document.write(findPairs(a, b, N, M));
// This code is contributed by saurabh_jaiswal.
</script>
Time Complexity: O(N + M)
Auxiliary Space: O(1)
Approach2 (Using Binary Search)
The approach in the provided code employs binary search to efficiently find matching elements between two sorted arrays. It finds both the leftmost and rightmost indices of a target element within a sorted array using a modified binary search algorithm. By performing two separate binary searches, the function identifies the leftmost occurrence of the target element first and then the rightmost occurrence.
Follow the steps to solve the problem:
- For each element in A, it call the binary search function to find the number of occurrences of that element in array B, and accumulate to calculate the total count of pairs with equal values.
- In binary search function,Initialize two pointers, left and right, to the beginning and end of the array respectively. Also, set variables leftIndex and rightIndex to store the leftmost and rightmost indices of the target element, initially set to the size of the array.
- Enter a while loop while the left pointer is less than or equal to the right pointer.
- Calculate the midpoint index using the formula mid = left + (right - left) / 2.
- Check if the element at the midpoint index is equal to the target element., If it is equal, update the leftIndex to the current midpoint index and move the right pointer to mid - 1 to search for the leftmost occurrence.
- If it is less than the target element, update the left pointer to mid + 1 to search the right half of the array.
- If it is greater than the target element, update the right pointer to mid - 1 to search the left half of the array.
- After finding the leftmost occurrence, reset the left and right pointers to the beginning and end of the array respectively. Perform a similar binary search to find the rightmost occurrence of the target element, updating the rightIndex accordingly.
- Finally, return the count of occurrences of the target element by calculating the difference between rightIndex and leftIndex plus 1. If the target element is not found, return 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// binary search
int binarySearch(const vector<int>& b, int x)
{
int left = 0, right = b.size() - 1,
leftIndex = b.size(), rightIndex = -1;
int count = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (b[mid] == x) {
leftIndex = mid;
right = mid - 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
left = 0, right = b.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (b[mid] == x) {
rightIndex = mid;
left = mid + 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return max(0, rightIndex - leftIndex + 1);
}
int countPairs(const vector<int>& a, const vector<int>& b)
{
int count = 0;
for (int i = 0; i < a.size(); i++) {
count += binarySearch(b, a[i]);
}
return count;
}
int main()
{
vector<int> a = { 1, 1, 3, 3, 3, 5, 8, 8 };
vector<int> b = { 1, 3, 3, 4, 5, 5, 5 };
int pairs = countPairs(a, b);
// Output
cout << pairs << endl;
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Binary search
static int binarySearch(int[] b, int x)
{
int left = 0, right = b.length - 1,
leftIndex = b.length, rightIndex = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (b[mid] == x) {
leftIndex = mid;
right = mid - 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
left = 0;
right = b.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (b[mid] == x) {
rightIndex = mid;
left = mid + 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return Math.max(0, rightIndex - leftIndex + 1);
}
static int countPairs(int[] a, int[] b)
{
int count = 0;
for (int i = 0; i < a.length; i++) {
count += binarySearch(b, a[i]);
}
return count;
}
public static void main(String[] args)
{
int[] a = { 1, 1, 3, 3, 3, 5, 8, 8 };
int[] b = { 1, 3, 3, 4, 5, 5, 5 };
int pairs = countPairs(a, b);
// Output
System.out.println(pairs);
}
}
Python
# binary search
def binary_search(b, x):
left, right = 0, len(b) - 1
left_index, right_index = len(b), -1
while left <= right:
mid = left + (right - left) // 2
if b[mid] == x:
left_index = mid
right = mid - 1
elif b[mid] < x:
left = mid + 1
else:
right = mid - 1
left, right = 0, len(b) - 1
while left <= right:
mid = left + (right - left) // 2
if b[mid] == x:
right_index = mid
left = mid + 1
elif b[mid] < x:
left = mid + 1
else:
right = mid - 1
return max(0, right_index - left_index + 1)
def count_pairs(a, b):
count = 0
for num in a:
count += binary_search(b, num)
return count
if __name__ == "__main__":
a = [1, 1, 3, 3, 3, 5, 8, 8]
b = [1, 3, 3, 4, 5, 5, 5]
pairs = count_pairs(a, b)
# Output
print(pairs)
# This code is contributed by Ayush Mishra
JavaScript
// Binary search
function binarySearch(b, x) {
let left = 0, right = b.length - 1,
leftIndex = b.length, rightIndex = -1;
while (left <= right) {
let mid = Math.floor(left + (right - left) / 2);
if (b[mid] === x) {
leftIndex = mid;
right = mid - 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
left = 0;
right = b.length - 1;
while (left <= right) {
let mid = Math.floor(left + (right - left) / 2);
if (b[mid] === x) {
rightIndex = mid;
left = mid + 1;
}
else if (b[mid] < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return Math.max(0, rightIndex - leftIndex + 1);
}
function countPairs(a, b) {
let count = 0;
for (let i = 0; i < a.length; i++) {
count += binarySearch(b, a[i]);
}
return count;
}
// Sample input
let a = [1, 1, 3, 3, 3, 5, 8, 8];
let b = [1, 3, 3, 4, 5, 5, 5];
let pairs = countPairs(a, b);
// Output
console.log(pairs);
Time Complexity : O( N log M)
Auxilary Space : O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem