## Ebay Interview Question

Software Engineer Interns**Country:**United States

**Interview Type:**Phone Interview

A possible approach:

1. Build a map of counters whose keys are the elements and the values are the appearance counters of each element.

2. Create an array of the map's entries - the entries are of the form (key,value) where key is an element and value is the counter of the number of times the element appeared.

3. Use the median of median algorithm to find the k-th highest entry according to value. This means that comparison between two entries is made according to their value fields (the counters).

4. Iterate over the array and return all the keys of the entries that have a higher value (counter) than the median counter we found in step 3. There should be at least k such elements (maybe more in case there are several elements whose counter is the median the counter - in this case we can either return all of them or just the first k elements we find).

Complexity: O(n) amortized (because of the counter map) run-time complexity (median of median is O(n) worst case). Space complexity is O(n) as well.

Assuming that there is an infinite stream of numbers and your are supposed to tell the k most occurring numbers, I am giving you an approach.

1. Maintain a Linked List with decreasing order of frequency. Each node of linked list will have the number and its frequency.

2. Maintain a hash map with key as number and value as the pointer to the node in the linked list.

3. If a new number comes, add it to the tail of the linked list, maintaing the hash map.

The cost of maintaining the list for every number is O(1).

Reason:

1. When the list is empty - add a node O(1)

2. When node is not in list - add a node O(1)

3. when frequency of a node changes, it moves before the previous node - O(1)

The cost of returning the top occurred (k) numbers - O(k) - returning the first k numbers from the linked list.

1. Create a frequency array of size (n + 1); where n is the maximum element in input array

2. For every element i, in the input array, increment the ith index in the frequency array by

3. Sort the frequency array in reverse order (decrementing).

4. The first k elements are the most frequent elements in the input array.

```
int[] array = new int[] { 1, 2, 1, 1, 3, 4, 5, 3, 3, 3, 3, 3, 5, 6, 7,
2, 9, 7, 5 };
int k = 3;
Integer frequency[] = new Integer[10];
Arrays.fill(frequency, 0);
for (int i = 0; i < frequency.length; i++) {
frequency[array[i]] += 1;
}
Arrays.sort(frequency, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (o1.intValue() < o2.intValue()) {
return 1;
} else if (o1.intValue() > o2.intValue()) {
return -1;
} else {
return 0;
}
};
});
for (int i = 0; i < k; i++) {
System.out.println(array[frequency[i]]);
}
```

in terms of MR it could be

- Oleg G April 22, 2014