I can think of sorting them and then going over each element one by one but this is nlogn. Is there a linear method to count distinct elements in a list?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: – distinct vs. unique
If you are looking for “unique” values (As in if you see an element “JASON” more than once, than it is no longer unique and should not be counted)
You can do that in linear time by using a HashMap 😉
(The generalized / language-agnostic idea is Hash table)
Each entry of a HashMap / Hash table is
<KEY, VALUE>pair where the keys are unique (but no restrictions on their corresponding value in the pair)Step 1:
Iterate through all elements in the list once: O(n)
Step2:
Iterate through the HashMap and count the KEYS with VALUE equal to exactly 1 (thus unique) O(n)
Analysis:
If, however, you are looking for “distinct” values (As in if you want to count how many different elements there are), use a HashSet instead of a HashMap / Hash table, and then simply query the size of the HashSet.