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
using System ; using System . Collections . Generic ; class GFG { static int M = 4 ; static int N = 5 ; static int findCommon ( int [ , ] mat ) { Dictionary < int , int > cnt = new Dictionary < int , int > ( ) ; int i , j ; for ( i = 0 ; i < M ; i ++ ) { if ( cnt . ContainsKey ( mat [ i , 0 ] ) ) { cnt [ mat [ i , 0 ] ] = cnt [ mat [ i , 0 ] ] + 1 ; } else { cnt . Add ( mat [ i , 0 ] , 1 ) ; } for ( j = 1 ; j < N ; j ++ ) { if ( mat [ i , j ] != mat [ i , j - 1 ] ) if ( cnt . ContainsKey ( mat [ i , j ] ) ) { cnt [ mat [ i , j ] ] = cnt [ mat [ i , j ] ] + 1 ; } else { cnt . Add ( mat [ i , j ] , 1 ) ; } } } foreach ( KeyValuePair < int , int > ele in cnt ) { if ( ele . Value == M ) return ele . Key ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ , ] mat = { { 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 ) Console . WriteLine ( " No ▁ common ▁ element " ) ; else Console . WriteLine ( " Common ▁ element ▁ is ▁ " + result ) ; } }