Find a common element in all rows of a given row | C ++ implementation of the approach ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; A hash map to store count of elements ; Increment the count of first element of the row ; Starting from the second element of the current row ; If current element is different from the previous element i . e . it is appearing for the first time in the current row ; Find element having count equal to number of rows ; No such element found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M  4 NEW_LINE #define N  5 NEW_LINE int findCommon ( int mat [ M ] [ N ] ) { unordered_map < int , int > cnt ; int i , j ; for ( i = 0 ; i < M ; i ++ ) { cnt [ mat [ i ] [ 0 ] ] ++ ; for ( j = 1 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) cnt [ mat [ i ] [ j ] ] ++ ; } } for ( auto ele : cnt ) { if ( ele . second == M ) return ele . first ; } return -1 ; } int main ( ) { int mat [ M ] [ N ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } , } ; int result = findCommon ( mat ) ; if ( result == -1 ) cout << " No ▁ common ▁ element " ; else cout << " Common ▁ element ▁ is ▁ " << result ; return 0 ; }