Count number of common elements between a sorted array and a reverse sorted array
Last Updated :
22 Mar, 2023
Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays.
Examples:
Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}
Output: 0
Input: A[] = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999}, B[] = {109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1}
Output: 4
Naive Approach:- Check for all elements in array A that is present in array B or not if Yes increase the count of pair.
Implementation:-
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of
// elements common in both the arrays
int countEqual(int A[], int B[], int N)
{
//variable to store answer
int ans=0;
//first loop for array A
for(int i=0;i<N;i++)
{
//This loop to find array A element in B
for(int j=0;j<N;j++)
{
//if found then increase count and exit the loop
if(A[i]==B[j])
{
ans++;
break;
}
}
}
return ans;
}
// Driver Code
int main()
{
int A[] = { 2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999 };
int B[] = { 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 };
int N = sizeof(A) / sizeof(int);
cout << countEqual(A, B, N);
return 0;
}
//This code contributed by shubhamrajput6156
Java
import java.io.*;
class GFG
{
// Java program for the above approach
// Function to count the number of
// elements common in both the arrays
public static int countEqual(int[] A, int[] B, int N)
{
// variable to store answer
int ans = 0;
// first loop for array A
for (int i = 0;i < N;i++)
{
// This loop to find array A element in B
for (int j = 0;j < N;j++)
{
// if found then increase count and exit the loop
if (A[i] == B[j])
{
ans++;
break;
}
}
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int[] A = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999};
int[] B = {109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1};
int N = A.length;
System.out.print(countEqual(A, B, N));
}
}
// This code contributed by bhardwajji
JavaScript
// JS code to implement the approach
// JavaScript code for the above approach
function countEqual(A, B, N)
{
// variable to store answer
let ans = 0;
// first loop for array A
for (let i = 0; i < N; i++)
{
// This loop to find array A element in B
for (let j = 0; j < N; j++)
{
// if found then increase count and exit the
// loop
if (A[i] == B[j]) {
ans++;
break;
}
}
}
return ans;
}
// Driver Code
let A = [ 2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999 ];
let B = [ 109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1 ];
let N = A.length;
console.log(countEqual(A, B, N));
// This code is contributed by phasing17
C#
// C# program for the above approach
using System;
class GFG
{
// Function to count the number of
// elements common in both the arrays
public static int countEqual(int[] A, int[] B, int N)
{
// variable to store answer
int ans = 0;
// first loop for array A
for (int i = 0;i < N;i++)
{
// This loop to find array A element in B
for (int j = 0;j < N;j++)
{
// if found then increase count and exit the loop
if (A[i] == B[j])
{
ans++;
break;
}
}
}
return ans;
}
// Driver Code
public static void Main()
{
int[] A = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999};
int[] B = {109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1};
int N = A.Length;
Console.WriteLine(countEqual(A, B, N));
}
}
// This code is contributed by Pushpesh Raj.
Python3
# python program for the above approach
# Function to count the number of
# elements common in both the arrays
def countEqual(A, B, N):
# variable to store answer
ans = 0
# first loop for array A
for i in range(N):
# This loop to find array A element in B
for j in range(N):
# if found then increase count and exit the loop
if A[i] == B[j]:
ans += 1
break
return ans
# driver code
A = [2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999]
B = [109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1]
N = len(A)
print(countEqual(A, B, N))
Time Complexity:- O(N^2)
Auxiliary Space:- O(1)
Approach: The given problem can be solved by using the Two Pointer Approach. Follow the steps below to solve the problem:
- Initialize two variables, say first as 0 and second as (N - 1) that is used to traverse the array A[] and B[] from the front and back respectively.
- Initialize a variable, say count as 0 that stores the count of numbers common in the array A[] and B[].
- Iterate a loop until first < N and second >= 0 and perform the following steps:
- If the value of A[first] is equal to B[second], then increment the values of count and first and decrement the value of the second.
- If the value of A[first] is less than B[second], then increment the value of first.
- If the value of A[first] is greater than B[second], then decrement the value of the second.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of
// elements common in both the arrays
int countEqual(int A[], int B[], int N)
{
// Used to traverse array A[] and
// B[] from the front and the back
int first = 0;
int second = N - 1;
// Stores the count of numbers
// common in both array
int count = 0;
while (first < N && second >= 0) {
// If A[first] is less than
// B[second]
if (A[first] < B[second]) {
// Increment the value
// of first
first++;
}
// IF B[second] is less
// than A[first]
else if (B[second] < A[first]) {
// Decrement the value
// of second
second--;
}
// A[first] is equal to
// B[second]
else {
// Increment the value
// of count
count++;
// Increment the value
// of first
first++;
// Decrement the value
// of second
second--;
}
}
// Return the value of count
return count;
}
// Driver Code
int main()
{
int A[] = { 2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999 };
int B[] = { 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 };
int N = sizeof(A) / sizeof(int);
cout << countEqual(A, B, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{
// Function to count the number of
// elements common in both the arrays
static int countEqual(int A[], int B[], int N)
{
// Used to traverse array A[] and
// B[] from the front and the back
int first = 0;
int second = N - 1;
// Stores the count of numbers
// common in both array
int count = 0;
while (first < N && second >= 0) {
// If A[first] is less than
// B[second]
if (A[first] < B[second]) {
// Increment the value
// of first
first++;
}
// IF B[second] is less
// than A[first]
else if (B[second] < A[first]) {
// Decrement the value
// of second
second--;
}
// A[first] is equal to
// B[second]
else {
// Increment the value
// of count
count++;
// Increment the value
// of first
first++;
// Decrement the value
// of second
second--;
}
}
// Return the value of count
return count;
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999 };
int B[] = { 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 };
int N = A.length;
System.out.println(countEqual(A, B, N));
}
}
// This code is contributed by susmitakundugoaldanga.
Python3
# Python program for the above approach
# Function to count the number of
# elements common in both the arrays
def countEqual(A, B, N) :
# Used to traverse array A[] and
# B[] from the front and the back
first = 0
second = N - 1
# Stores the count of numbers
# common in both array
count = 0
while (first < N and second >= 0) :
# If A[first] is less than
# B[second]
if (A[first] < B[second]) :
# Increment the value
# of first
first += 1
# IF B[second] is less
# than A[first]
elif (B[second] < A[first]) :
# Decrement the value
# of second
second -= 1
# A[first] is equal to
# B[second]
else :
# Increment the value
# of count
count += 1
# Increment the value
# of first
first += 1
# Decrement the value
# of second
second -= 1
# Return the value of count
return count
# Driver Code
A= [ 2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999 ]
B = [ 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 ]
N = len(A)
print(countEqual(A, B, N))
# This code is contributed by sanjou_62.
C#
// C# program for the above approach
using System;
class GFG{
// Function to count the number of
// elements common in both the arrays
static int countEqual(int[] A, int[] B, int N)
{
// Used to traverse array A[] and
// B[] from the front and the back
int first = 0;
int second = N - 1;
// Stores the count of numbers
// common in both array
int count = 0;
while (first < N && second >= 0)
{
// If A[first] is less than
// B[second]
if (A[first] < B[second])
{
// Increment the value
// of first
first++;
}
// IF B[second] is less
// than A[first]
else if (B[second] < A[first])
{
// Decrement the value
// of second
second--;
}
// A[first] is equal to
// B[second]
else
{
// Increment the value
// of count
count++;
// Increment the value
// of first
first++;
// Decrement the value
// of second
second--;
}
}
// Return the value of count
return count;
}
// Driver code
static void Main()
{
int[] A = { 2, 4, 5, 8, 12, 13,
17, 18, 20, 22, 309, 999 };
int[] B = { 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 };
int N = A.Length;
Console.WriteLine(countEqual(A, B, N));
}
}
// This code is contributed by abhinavjain194
JavaScript
<script>
// Javascript program for the above approach
// Function to count the number of
// elements common in both the arrays
function countEqual(A, B, N)
{
// Used to traverse array A[] and
// B[] from the front and the back
let first = 0;
let second = N - 1;
// Stores the count of numbers
// common in both array
let count = 0;
while (first < N && second >= 0) {
// If A[first] is less than
// B[second]
if (A[first] < B[second]) {
// Increment the value
// of first
first++;
}
// IF B[second] is less
// than A[first]
else if (B[second] < A[first]) {
// Decrement the value
// of second
second--;
}
// A[first] is equal to
// B[second]
else {
// Increment the value
// of count
count++;
// Increment the value
// of first
first++;
// Decrement the value
// of second
second--;
}
}
// Return the value of count
return count;
}
// Driver Code
let A = [2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999];
let B = [109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1];
let N = A.length;
document.write(countEqual(A, B, N));
// This code is contributed _saurabh_jaiswal
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach : We will use Binary search to check if the element of array B[] is present in the array A[] or not because array A[] is already sorted in increasing order. So , we can use binary search for finding elements.
Below is the implementation of the above approach :
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
//Function to check if x is present in the array or not
bool binarysearch(int arr[], int N, int x)
{
int l = 0, r = N - 1;
while (l <= r) {
int mid = (l + r) / 2;
// Checking if the middle element is equal to x
if (arr[mid] == x) {
return true;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
// return true , if element x is present in the array
// else false
return false;
}
// Function to count the number of
// elements common in both the arrays
int countEqual(int A[], int B[], int N, int M)
{ int count = 0;
// Iterate each element of array B
for (int i = 0; i < M; i++)
{
// Checking if the element of array B is present in
// array A using the binary search
if (binarysearch(A, N, B[i]))
{
count++;
}
}
// Return count of common element
return count;
}
// Driver Code
int main()
{
int A[] = { 2, 4, 5, 8, 12, 13, 17,
18, 20, 22, 309, 999 };
int B[] = { 109, 99, 68, 54, 22
, 19,17, 13, 11, 5, 3, 1 };
int N = sizeof(A) / sizeof(int);
int M = sizeof(B) / sizeof(int);
//Function call
cout << countEqual(A, B, N, M)<<endl;
return 0;
}
// This code is contributed by nikhilsainiofficial546
Java
// Java program for the above approach
import java.util.Arrays;
class Main {
// Function to check if x is present in the array or not
static boolean binarySearch(int[] arr, int N, int x) {
int l = 0, r = N - 1;
while (l <= r) {
int mid = (l + r) / 2;
// Checking if the middle element is equal to x
if (arr[mid] == x) {
return true;
} else if (arr[mid] < x) {
l = mid + 1;
} else {
r = mid - 1;
}
}
// return true , if element x is present in the array
// else false
return false;
}
// Function to count the number of elements common in both the arrays
static int countEqual(int[] A, int[] B, int N, int M) {
int count = 0;
// Sort array A
Arrays.sort(A);
// Iterate each element of array B
for (int i = 0; i < M; i++) {
// Checking if the element of array B is present in array A using the binary search
if (binarySearch(A, N, B[i])) {
count++;
}
}
// Return count of common element
return count;
}
// Driver Code
public static void main(String[] args) {
int[] A = { 2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999 };
int[] B = { 109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1 };
int N = A.length;
int M = B.length;
//Function call
System.out.println(countEqual(A, B, N, M));
}
}
Python3
#Python program for the above approach
# Function to check if x is present in the array or not
def binarySearch(arr, N, x):
l = 0
r = N - 1
while l <= r:
mid = (l + r) // 2
# Checking if the middle element is equal to x
if arr[mid] == x:
return True
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
# return true , if element x is present in the array
# else false
return False
# Function to count the number of elements common in both the arrays
def countEqual(A, B, N, M):
count = 0
# Sort array A
A.sort()
# Iterate each element of array B
for i in range(M):
# Checking if the element of array B is present in array A using the binary search
if binarySearch(A, N, B[i]):
count += 1
# Return count of common element
return count
# Driver Code
A = [ 2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999 ]
B = [ 109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1 ]
N = len(A)
M = len(B)
#Function call
print(countEqual(A, B, N, M))
C#
// C# program for the above approach
using System;
class Program
{
// Function to check if x is present in the array or not
static bool BinarySearch(int[] arr, int N, int x)
{
int l = 0, r = N - 1;
while (l <= r) {
int mid = (l + r) / 2;
// Checking if the middle element is equal to x
if (arr[mid] == x) {
return true;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
// return true , if element x is present in the
// array else false
return false;
}
// Function to count the number of
// elements common in both the arrays
static int CountEqual(int[] A, int[] B, int N, int M)
{
int count = 0;
// Iterate each element of array B
for (int i = 0; i < M; i++) {
// Checking if the element of array B is present
// in array A using the binary search
if (BinarySearch(A, N, B[i])) {
count++;
}
}
// Return count of common element
return count;
}
// Driver Code
static void Main()
{
int[] A = { 2, 4, 5, 8, 12, 13,
17, 18, 20, 22, 309, 999 };
int[] B = { 109, 99, 68, 54, 22, 19,
17, 13, 11, 5, 3, 1 };
int N = A.Length;
int M = B.Length;
// Function call
Console.WriteLine(CountEqual(A, B, N, M));
Console.ReadLine();
}
}
JavaScript
// JavaScript program to implement the approach
// Function to check if x is present in the array or not
function binarysearch(arr, N, x) {
let l = 0, r = N - 1;
while (l <= r) {
let mid = Math.floor((l + r) / 2);
// Checking if the middle element is equal to x
if (arr[mid] === x) {
return true;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
// return true , if element x is present in the array
// else false
return false;
}
// Function to count the number of
// elements common in both the arrays
function countEqual(A, B, N, M) {
let count = 0;
// Iterate each element of array B
for (let i = 0; i < M; i++) {
// Checking if the element of array B is present in
// array A using the binary search
if (binarysearch(A, N, B[i])) {
count++;
}
}
// Return count of common element
return count;
}
// Driver Code
(() => {
const A = [2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999];
const B = [109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1];
const N = A.length;
const M = B.length;
// Function call
console.log(countEqual(A, B, N, M));
})();
// This code is contributed by phasing17
Time Complexity: O(M*log(N))
Auxiliary Space: O(1)
Similar Reads
Count number of common elements between two arrays Given two arrays a[] and b[], the task is to find the count of common elements in both the given arrays. Note that both the arrays contain distinct (individually) positive integers.Examples: Input: a[] = {1, 2, 3}, b[] = {2, 4, 3} Output: 2 2 and 3 are common to both the arrays.Input: a[] = {1, 4, 7
15 min read
Count Array elements that occur before any of its prefix value of another Array Given two arrays A[] and B[] of size N each, the task is to find the number of elements in array B[] that occur before any element that was present before it in array A[]. Example: Input: N = 5, A[] = {3, 5, 1, 2, 4}, B[] = {4, 3, 1, 5, 2}Output: 2Explanation: Array A represent that 3 comes first th
6 min read
Count number of elements between two given elements in array Given an unsorted array of n elements and also given two points num1 and num2. The task is to count number of elements occurs between the given points (excluding num1 and num2). If there are multiple occurrences of num1 and num2, we need to consider leftmost occurrence of num1 and rightmost occurren
7 min read
Construct Binary Array having same number of unequal elements with two other Arrays Given two binary arrays A[] and B[] of size N, the task is to construct the lexicographically smallest binary array X[] such that the number of non-equal elements in A and X is equal to the number of non-equal elements in B and X. If such an array does not exist return -1. Note: If there are multipl
12 min read
Number of moves required between the arrays to complete the traversal in sorted order Given two sorted arrays, X[] of size N and Y[] of size M having unique values. The task is to count the total number of moves required between the arrays to traverse all the elements in both the arrays in ascending order if initially, the traversal starts from the X[] array. Examples: Input: X[] = {
11 min read
Generate array having differences between count of occurrences of every array element on its left and right Given an array A[] consisting of N integers, the task is to construct an array B[] such that for every ith index, B[i] = X - Y, where X and Y are the count of occurrences of A[i] after and before the ith index. Examples: Input: A[] = {3, 2, 1, 2, 3}Output: 1 1 0 -1 -1Explanation: arr[0] = 3, X = 1,
6 min read
Count distinct elements from a range of a sorted sequence from a given frequency array Given two integers L and R and an array arr[] consisting of N positive integers( 1-based indexing ) such that the frequency of ith element of a sorted sequence, say A[], is arr[i]. The task is to find the number of distinct elements from the range [L, R] in the sequence A[]. Examples: Input: arr[] =
13 min read
Print elements of an array according to the order defined by another array | set 2 Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at
7 min read
Count of smaller or equal elements in sorted array Given a sorted array of size n. Find a number of elements that are less than or equal to a given element. Examples: Input : arr[] = {1, 2, 4, 5, 8, 10} key = 9 Output : 5 Elements less than or equal to 9 are 1, 2, 4, 5, 8 therefore result will be 5. Input : arr[] = {1, 2, 2, 2, 5, 7, 9} key = 2 Outp
15+ min read
Find just strictly greater element from first array for each element in second array Given two arrays A[] and B[] containing N elements, the task is to find, for every element in the array B[], the element which is just strictly greater than that element which is present in the array A[]. If no value is present, then print 'null'. Note: The value from the array A[] can only be used
10 min read