Add mat from i to j and vice versa , if possible . Since length of each contact field is at max some constant . ( say 30 ) so body execution of this for loop takes constant time .
for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] . field1 == arr [ j ] . field1 or arr [ i ] . field1 == arr [ j ] . field2 or arr [ i ] . field1 == arr [ j ] . field3 or arr [ i ] . field2 == arr [ j ] . field1 or arr [ i ] . field2 == arr [ j ] . field2 or arr [ i ] . field2 == arr [ j ] . field3 or arr [ i ] . field3 == arr [ j ] . field1 or arr [ i ] . field3 == arr [ j ] . field2 or arr [ i ] . field3 == arr [ j ] . field3 ) : NEW_LINE INDENT mat [ i ] [ j ] = 1 NEW_LINE mat [ j ] [ i ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT