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 ; An array to store indexes of current last column ; Initialize min_row as first row ; Keep finding min_row in current last column , till either all elements of last column become same or we hit first column . ; Find minimum in current last column ; eq_count is count of elements equal to minimum in current last column . ; Traverse current last column elements again to update it ; Decrease last column index of a row whose value is more than minimum . ; Reduce last column index by 1 ; If equal count becomes M , return the value ; Driver Code
M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT column = [ N - 1 ] * M NEW_LINE min_row = 0 NEW_LINE while ( column [ min_row ] >= 0 ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) : NEW_LINE INDENT min_row = i NEW_LINE DEDENT DEDENT eq_count = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ column [ i ] ] > mat [ min_row ] [ column [ min_row ] ] ) : NEW_LINE INDENT if ( column [ i ] == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT column [ i ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT eq_count += 1 NEW_LINE DEDENT DEDENT if ( eq_count == M ) : NEW_LINE INDENT return mat [ min_row ] [ column [ min_row ] ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT 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 DEDENT