How do you find the k most frequent elements in a list?
Count the occurrences first, then select the k entries with the highest counts. The interesting part is the selection step, and there are two good ways to do it.
The heap approach keeps a min heap of size k of the entries seen so far. As you walk the counts, if the current entry has a higher count than the smallest in the heap, replace that smallest entry. At the end the heap holds the k most frequent items. The bucket approach groups the entries by count, so you build a list of buckets where bucket number j holds the items that appear j times, and then you walk the buckets from the highest count down collecting items until you have k of them.
The mechanism is that once you have the counts, the problem becomes selecting the k largest values of a small collection, and both approaches exploit that structure. The heap avoids sorting the whole count table, and the bucket sort exploits the fact that the counts are bounded by the length of the input.
The trade-off to name is that the heap approach is O of n log k time, where n is the number of items and k the number you want, while the bucket approach is O of n time because the buckets are bounded by the maximum frequency. The bucket approach does need that extra array of buckets, which is proportional to the maximum count. If k is close to the number of distinct items, sorting the counts is also perfectly reasonable and is the simplest of the three to write.