Medium · Frequency Map + Heap
Understand → Visualise → Practice.
Frequency counting reduces a long array to one record per distinct value. A heap then selects the k highest-frequency records.
Order candidates by higher frequency first and, for ties, smaller value first.
Build value → frequency.
Use frequency as the main heap key.
Return the best k with deterministic tie-breaking.
O(n + u log k) time and O(u) space for u distinct values.
State a tie rule; otherwise several different outputs can all seem correct.
Read the full guide first: Heaps and Priority Queues.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.