Medium Hashing

Most Frequent Elements

Receives an array of integers and a number k, and returns the k most frequent values ordered from highest to lowest frequency. It runs in O(n) using bucket sort: first it counts every value's frequency in a hash map, then it scatters each value into a bucket indexed by its frequency (so all values that appear the same number of times share a bucket), and finally it reads the buckets from the highest frequency down, collecting values until it has k of them. Returns a new array with the k most frequent values, most frequent first; when several values tie in frequency any order between the tied ones is valid. If k is greater than or equal to the number of distinct values it returns every distinct value, and an empty input yields an empty array.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References