Skip to content
BytePatterns

K Most Frequent Values

MediumTwo Heaps & K-Way Merge#top-k#min-heap#hash-map~25m

Problem

Given a list of whole numbers and a count k, return the k values that appear most often. Order the result from most to least frequent, and when two values appear equally often, put the smaller value first. You may assume k is at least 1 and no larger than the number of distinct values.

Examples

Input:  values = [4, 1, 4, 2, 1, 4, 3], k = 2
Output: [4, 1]
Why:    4 appears three times and 1 twice
Input:  values = [7, 8, 9, 8, 9], k = 1
Output: [8]
Why:    8 and 9 tie at two each, and 8 is smaller
Input:  values = [5], k = 1
Output: [5]
Why:    edge case, a single value

Hints

0 / 3

Stuck on the idea rather than the code? Top K in a Stream covers it.