LinkedIn Interview Question

Given an array with duplicate elements give an algorithm to get the count of distinct elements in the array

Interview Answers

Anonymous

Mar 19, 2012

a good one would be HashSet, add all elements into the HashSet and return HashSet's size

11

Anonymous

Feb 14, 2011

Whats N, size of the given array? What if there are elements in the array taht are larger than N? A better strategy would be to simply use a hashmap to put the elements and their counts. everytime you see the number you increment the count. this runs in order n space and time.

3

Anonymous

Dec 16, 2014

Just add all the numbers to a Set and return the sum of all numbers from the Set. Set automatically de-duplicates the numbers.

Anonymous

Jan 22, 2011

create another array initialized to N with 0 in each slot. Go through the first array, each time you see a number, add that number to the respective index in the second array. Then after, just count the number of elements that aren't 0. This runs in O(n).

1