Question presented to candidate: "Given a list of integers and a number k, return the k values that appear most often. If two values appear the same number of times, put the smaller value first. Write it in Python and tell me the complexity."
What a strong answer should cover:
- Two steps: count with a hash map in O(n), then pick the k biggest counts.
- Three ways to pick: sort the m distinct values (O(m log m)), a size-k min-heap (O(m log k)), or bucket sort by count (O(n)) because a count is at most n.
- Ties: encode the rule in the key โ here the heap key
(count, -value)makes the weakest entry the lowest count, then the larger value. - Edge cases: k equal to the number of distinct values, ties at the cut-off, negative numbers.
- Python specifics:
collections.Counter, and thatCounter.most_common(k)breaks ties by first appearance, not by value;heapqis a min-heap, so tuples(count, -value)give the right weakest-first order;heapq.nlargest(k, counts, key=...)as the one-liner.
Clarifying questions expected:
- How should ties be ordered, and must the result be sorted by frequency?
- Is k always at most the number of distinct values?
Code / implementation expected: Yes โ Counter plus a size-k heapq, and the bucket-sort version if asked for O(n), in Python.