← All Exercises

Top K Frequent Numbers with a PriorityQueue

intermediatejava~20min

Background

A heap keeps extra memory at O(k) while scanning a potentially large frequency map. Tie-breaking rules are where most top-k implementations go wrong.

Problem

Given an integer array and k, return the k most frequent values. Order results by frequency descending, then value ascending, using a bounded min-heap rather than a full sort.

Input

A non-empty int array and a positive k no larger than the number of distinct values; values may repeat and may be negative.

Output

A list of exactly k integers ordered by frequency descending then value ascending.

Sample tests

Sample 1

Input: values 4,4,4,2,2,3,1,1,1,5 with k=2
Expected: [1, 4]

Sample 2

Input: values 1,2,3 with k=3
Expected: [1, 2, 3]

Your solution

Learning objective

Combine a frequency map with a bounded min-heap and explicit tie-break rules for deterministic top-k selection.