Count number of common elements between two arrays by using Bitset and Bitwise operation | C ++ implementation of the approach ; Function to return the count of common elements ; Traverse the first array ; Set 1 at position a [ i ] ; Traverse the second array ; Set 1 at position b [ i ] ; Bitwise AND of both the bitsets ; Find the count of 1 's ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  100000 NEW_LINE bitset < MAX > bit1 , bit2 , bit3 ; int count_common ( int a [ ] , int n , int b [ ] , int m ) { for ( int i = 0 ; i < n ; i ++ ) { bit1 . set ( a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { bit2 . set ( b [ i ] ) ; } bit3 = bit1 & bit2 ; int count = bit3 . count ( ) ; return count ; } 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 ; }