DSA interview question
A music app wants the k most-played songs from a play log (song IDs, with repeats). Counting plays is a hash map. Choosing the top k by count is where a heap helps: keep a min-heap of size k ordered by count, so the weakest of the current top k sits on top and is evicted whenever a more frequent song appears. That's O(n log k), and a bucket sort by frequency does it in O(n). In this version ties are broken toward the smaller ID, and the answer is listed from most to least frequent.
Example: [1, 1, 1, 2, 2, 3], k = 2 → [1, 2].
vector<int> topKFrequent(const vector<int>& nums, int k); // most frequent first; ties: smaller value first
Input (nums, k) | Output | Explanation |
|---|---|---|
([1, 1, 1, 2, 2, 3], 2) | [1, 2] | Counts 3, 2, 1 |
([1], 1) | [1] | |
([4, 4, 5, 5, 5, 6], 1) | [5] | |
([1, 2, 2, 3, 3, 3], 3) | [3, 2, 1] | |
([-1, -1, 7], 1) | [-1] |
(Confirm: k is at most the number of distinct values; this version orders the output by frequency, then by value.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in