Find a common element in all rows of a given row | Python3 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
from collections import defaultdict NEW_LINE M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT global M NEW_LINE global N NEW_LINE cnt = dict ( ) NEW_LINE cnt = defaultdict ( lambda : 0 , cnt ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < M ) : NEW_LINE INDENT cnt [ mat [ i ] [ 0 ] ] = cnt [ mat [ i ] [ 0 ] ] + 1 NEW_LINE j = 1 NEW_LINE while ( j < N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) : NEW_LINE INDENT cnt [ mat [ i ] [ j ] ] = cnt [ mat [ i ] [ j ] ] + 1 NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT for ele in cnt : NEW_LINE INDENT if ( cnt [ ele ] == M ) : NEW_LINE INDENT return ele NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 2 , 4 , 5 , 8 , 10 ] , [ 3 , 5 , 7 , 9 , 11 ] , [ 1 , 3 , 5 , 7 , 9 ] , ] NEW_LINE result = findCommon ( mat ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " No ▁ common ▁ element " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Common ▁ element ▁ is ▁ " , result ) NEW_LINE DEDENT