Skip to content
Related Articles

Related Articles

Count number of common elements between two arrays

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 24 Nov, 2022
Improve Article
Save Article

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 and 3 are common to both the arrays.
Input: a[] = {1, 4, 7, 2, 3}, b[] = {2, 11, 7, 4, 15, 20, 24} 
Output:
 

 

Approach 1: We will use 3 bitset of same size. First we will traverse first array and set the bit 1 to position a[i] in first bitset. 
After that we will traverse second array and set the bit 1 to position b[i] in second bitset. 
At last we will find the bitwise AND of both the bitsets and if the ith position of the resultant bitset is 1 then it implies that ith position of first and second bitsets are also 1 and i is the common element in both the arrays.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 100000
bitset<MAX> bit1, bit2, bit3;
 
// Function to return the count of common elements
int count_common(int a[], int n, int b[], int m)
{
 
    // Traverse the first array
    for (int i = 0; i < n; i++) {
 
        // Set 1 at position a[i]
        bit1.set(a[i]);
    }
 
    // Traverse the second array
    for (int i = 0; i < m; i++) {
 
        // Set 1 at position b[i]
        bit2.set(b[i]);
    }
 
    // Bitwise AND of both the bitsets
    bit3 = bit1 & bit2;
 
    // Find the count of 1's
    int count = bit3.count();
 
    return count;
}
 
// Driver code
int main()
{
 
    int a[] = { 1, 4, 7, 2, 3 };
    int b[] = { 2, 11, 7, 4, 15, 20, 24 };
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
 
    cout << count_common(a, n, b, m);
 
    return 0;
}

Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
public class GFG {
  static int bit1 = 0;
  static int bit2 = 0;
  static int bit3 = 0;
 
  // Function to return the count of common elements
  static int count_common(int[] a, int n, int[] b, int m)
  {
 
    // Traverse the first array
    for (int i = 0; i < n; i++) {
      // Set 1 at (index)position a[i]
      bit1 = bit1 | (1 << a[i]);
    }
    // Traverse the second array
    for (int i = 0; i < m; i++) {
 
      // Set 1 at (index)position b[i]
      bit2 = bit2 | (1 << b[i]);
    }
 
    // Bitwise AND of both the bitsets
    bit3 = bit1 & bit2;
 
    // Find the count of 1's
    int count = Integer.toBinaryString(bit3).split("1").length - 1;
    return count;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] a = { 1, 4, 7, 2, 3 };
    int[] b = { 2, 11, 7, 4, 15, 20, 24 };
    int n = a.length;
    int m = b.length;
 
    System.out.println(count_common(a, n, b, m));
  }
}
 
// This code is contributed by aadityaburujwale.

Python3




# Python3 implementation of the approach
 
MAX = 100000
bit1 , bit2, bit3 = 0, 0, 0
 
# Function to return the count of common elements
def count_common(a, n, b, m) :
 
    # Traverse the first array
    for i in range(n) :
         
        global bit1, bit2, bit3
         
        # Set 1 at (index)position a[i]
        bit1 = bit1 | (1<<a[i])
 
    # Traverse the second array
    for i in range(m) :
 
        # Set 1 at (index)position b[i]
        bit2 = bit2 | (1<<b[i])
 
    # Bitwise AND of both the bitsets
    bit3 = bit1 & bit2;
 
    # Find the count of 1's
    count = bin(bit3).count('1');
 
    return count;
 
# Driver code
if __name__ == "__main__" :
 
    a = [ 1, 4, 7, 2, 3 ];
    b = [ 2, 11, 7, 4, 15, 20, 24 ];
    n = len(a);
    m = len(b);
 
    print(count_common(a, n, b, m));
 
# This code is contributed by AnkitRai01

C#




// C# implementation of the approach
using System;
 
class GFG {
  static int bit1 = 0;
  static int bit2 = 0;
  static int bit3 = 0;
 
  // Function to return the count of common elements
  static int count_common(int[] a, int n, int[] b, int m)
  {
 
    // Traverse the first array
    for (int i = 0; i < n; i++) {
      // Set 1 at (index)position a[i]
      bit1 = bit1 | (1 << a[i]);
    }
    // Traverse the second array
    for (int i = 0; i < m; i++) {
 
      // Set 1 at (index)position b[i]
      bit2 = bit2 | (1 << b[i]);
    }
 
    // Bitwise AND of both the bitsets
    bit3 = bit1 & bit2;
 
    // Find the count of 1's
    var count
      = Convert.ToString(bit3, 2).Split("1").Length
      - 1;
    return count;
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int[] a = { 1, 4, 7, 2, 3 };
    int[] b = { 2, 11, 7, 4, 15, 20, 24 };
    int n = a.Length;
    int m = b.Length;
 
    Console.WriteLine(count_common(a, n, b, m));
  }
}
 
// This code is contributed by phasing17

Javascript




//JavaScript implementation of the approach
 
const MAX = 100000;
let bit1 = 0;
let bit2 = 0;
let bit3 = 0;
 
// Function to return the count of common elements
function count_common(a, n, b, m)
{
 
    // Traverse the first array
    for (var i = 0; i < n; i++)
    {
        // Set 1 at (index)position a[i]
        bit1 = bit1 | (1<<a[i]);
    }
    // Traverse the second array
    for (var i = 0; i < m; i++)
    {
 
        // Set 1 at (index)position b[i]
        bit2 = bit2 | (1<<b[i]);
    }
 
    // Bitwise AND of both the bitsets
    bit3 = bit1 & bit2;
 
    // Find the count of 1's
    var count = bit3.toString(2).split("1").length - 1;
    return count;
}
 
 
// Driver code
var a = [ 1, 4, 7, 2, 3 ];
var b = [ 2, 11, 7, 4, 15, 20, 24 ];
var n = a.length;
var m = b.length;
 
console.log(count_common(a, n, b, m));
 
//This code is contributed by phasing17

Output: 

3

 

Time Complexity: O(n + m)

Auxiliary Space: O(MAX)

Approach 2: We can also use hashmap to store frequencies of each element of both arrays a[] and b[] and sum up the minimum value for each element’s frequency.

Follow given steps to solve the problem:

1. Traverse array a[] and store all frequencies in map freq1.

2. Traverse array b[] and store all frequencies in map freq2.

3. Traverse the map freq1 and sum up the minimum value between x.second and freq2[x.first] in result.

4. Return result as the final answer.

C++14




#include <bits/stdc++.h>
using namespace std;
 
int count_common(int *a, int& n, int *b, int& m)
{
    unordered_map<int,int>freq1,freq2;
    int result=0;
     
    for(int i=0;i<n;i++)
        freq1[a[i]]++;
     
    for(int i=0;i<m;i++)
        freq2[b[i]]++;
     
    for(auto& x:freq1)
        result+=min(x.second,freq2[x.first]);
     
    return result;
}
 
// driver's code
int main()
{
    int a[]={1,2,3};
    int n=sizeof(a)/sizeof(a[0]);
    int b[]={2,4,3};
    int m=sizeof(b)/sizeof(b[0]);
     
    cout<<count_common(a,n,b,m);
 
    return 0;
}
// this code is contributed by prophet1999

Time Complexity: O(n+m)

Auxiliary Space: O(n+m)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!