Find a common element in all rows of a given row | 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
let M = 4 ; let N = 5 ; function findCommon ( mat ) { let cnt = new Map ( ) ; let i , j ; for ( i = 0 ; i < M ; i ++ ) { if ( cnt . has ( mat [ i ] [ 0 ] ) ) { cnt . set ( mat [ i ] [ 0 ] , cnt . get ( mat [ i ] [ 0 ] ) + 1 ) ; } else { cnt . set ( mat [ i ] [ 0 ] , 1 ) ; } for ( j = 1 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) { if ( cnt . has ( mat [ i ] [ j ] ) ) { cnt . set ( mat [ i ] [ j ] , cnt . get ( mat [ i ] [ j ] ) + 1 ) ; } else { cnt . set ( mat [ i ] [ j ] , 1 ) ; } } } } for ( let [ key , value ] of cnt . entries ( ) ) { if ( value == M ) return key ; } return - 1 ; } let mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 2 , 4 , 5 , 8 , 10 ] , [ 3 , 5 , 7 , 9 , 11 ] , [ 1 , 3 , 5 , 7 , 9 ] , ] let result = findCommon ( mat ) ; if ( result == - 1 ) document . write ( " " ) ; else document . write ( " " + result ) ;