Start by clarifying the problem constraints (e.g., input size, value range, whether ties matter) and then walk through a solution using a hash map to count frequencies followed by a heap or bucket sort to extract the top k. Emphasize the trade-offs between different approaches (e.g., O(n log k) heap vs O(n) bucket sort) and how to generalize from k=3 to any k.
Pro tip: Demonstrate awareness of edge cases (e.g., k equals number of unique elements, negative numbers, large input) and mention that for small k like 3, a simple sort might suffice, but for general k, a more efficient method is preferred. This shows you consider practical constraints and scalability.
Ask about input size, value range, whether the array can be empty, and if k is always valid. Confirm that the output order doesn't matter unless specified.
Propose using a hash map to count frequencies, then sort the unique elements by frequency and take the top k. Mention this is O(n + m log m) where m is unique elements.
Introduce a min-heap of size k to keep track of the top k frequent elements, achieving O(n log k) time. Alternatively, mention bucket sort for O(n) time when frequencies are bounded by n.
Compare heap vs bucket sort based on constraints: heap is simpler and works for any k, bucket sort is faster but requires frequency range. For k=3, a simple sort might be acceptable.
Trace the chosen algorithm on a small example (e.g., [1,1,1,2,2,3], k=2) and then write clean code, handling edge cases like k=0 or empty array.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.