Count distinct elements in an array | Python3 program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver Code
def countDistinct ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE res = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT while ( i < n - 1 and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT res += 1 ; NEW_LINE i += 1 ; NEW_LINE 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