Count of equal value pairs from given two Arrays such that a[i] equals b[j]
Last Updated :
09 May, 2024
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
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
Two Pointers Technique in Different languages
Java Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Letâs see the naive so
4 min read
C Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Letâs see the naive so
3 min read
Problems based on Two-Pointer Technique
Find four elements that sum to a given value | Two-Pointer approach
Given an array arr of integers of size N and a target number, the task is to find all unique quadruplets in it, whose sum is equal to the target number. Examples:Input: arr[] = {4, 1, 2, -1, 1, -3], target = 1 Output: [[-3, -1, 1, 4], [-3, 1, 1, 2]] Explanation: Both the quadruplets sum equals to ta
10 min read
Rearrange an array in maximum minimum form using Two Pointer Technique
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2
6 min read
Pair with largest sum which is less than K in the array
Given an array arr of size N and an integer K. The task is to find the pair of integers such that their sum is maximum and but less than K Examples: Input : arr = {30, 20, 50} , K = 70 Output : 30, 20 30 + 20 = 50, which is the maximum possible sum which is less than K Input : arr = {5, 20, 110, 100
10 min read
Longest increasing sequence by the boundary elements of an Array
Given an array arr[] of length N with unique elements, the task is to find the length of the longest increasing subsequence that can be formed by the elements from either end of the array.Examples: Input: arr[] = {3, 5, 1, 4, 2} Output: 4 Explanation: The longest sequence is: {2, 3, 4, 5} Pick 2, Se
8 min read
Two Sum - Pair with given Sum
Given an array arr[] of n integers and a target value, the task is to find whether there is a pair of elements in the array whose sum is equal to target. This problem is a variation of 2Sum problem.Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: trueExplanation: There is a pair (1, -3
15+ min read