Return the k most frequent values plus any ties with the kth
A streaming service logs the id of every title a viewer starts. The “Trending now” row shows the most started titles, but product does not want a title left out just because it tied with the last one shown: if the 3rd and 4th titles were started equally often, both appear.
Implement topFrequent(values, k). It returns the k most frequent values in values, plus every value tied with the k-th one.
topFrequent(values, k) // => array of distinct values
values is an array of integers (negative numbers and 0 included). k is a non-negative integer.values.k ranked values. Then also include every further value whose count equals the count of the k-th value. The result can be longer than k.k or fewer distinct values, return all of them, ranked.[] when k is 0 or values is empty.values.values can hold 30,000 items with thousands of distinct values, so counting each distinct value with its own pass over the array is too slow.const starts = [3, 1, 3, 2, 1, 4, 3, 2];
// counts: 3 -> 3 times, 1 -> 2, 2 -> 2, 4 -> 1
topFrequent(starts, 1); // => [3]
topFrequent(starts, 2); // => [3, 1, 2] (2 ties with 1, the 2nd value)
topFrequent(starts, 3); // => [3, 1, 2]
topFrequent(starts, 4); // => [3, 1, 2, 4]
topFrequent(starts, 9); // => [3, 1, 2, 4] (only 4 distinct values)
topFrequent([7, -2, 7, -2, 0], 1); // => [7, -2] (7 appears first)
topFrequent([5, 6, 7], 2); // => [5, 6, 7] (all tied at 1)
topFrequent([1, 1], 0); // => []