Count distinct elements in an array | This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver code
def countDistinct ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in s ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDistinct ( arr , n ) ) NEW_LINE