Find k most frequent elements, discuss O(n)
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Find k most frequent elements, discuss O(n) evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- 1 <= k <= number of distinct values in nums
- The k most-frequent values are uniquely determined for the given inputs
Examples
Input: ([1, 1, 1, 2, 2, 3], 2)
Expected Output: [1, 2]
Explanation: 1 appears 3 times and 2 appears 2 times — the two most frequent. 3 appears once and is excluded.
Input: ([1], 1)
Expected Output: [1]
Explanation: Single element; the only value is the most frequent.
Input: ([4, 4, 4, 6, 6, 6, 6, 7, 7], 2)
Expected Output: [6, 4]
Explanation: Frequencies: 6->4, 4->3, 7->2. Top 2 ordered by frequency descending: [6, 4].
Input: ([-1, -1, -1, -2, -2, 5], 1)
Expected Output: [-1]
Explanation: -1 occurs 3 times, more than -2 (2) and 5 (1); negatives are handled like any other value.
Input: ([5, 5, 5, 5, 5], 1)
Expected Output: [5]
Explanation: Only one distinct value, repeated five times.
Input: ([10, 20, 30, 40], 4)
Expected Output: [10, 20, 30, 40]
Explanation: All values distinct with frequency 1; k equals the number of distinct values, so all are returned (ties broken by value ascending).
Input: ([3, 3, 2, 2, 1, 1], 3)
Expected Output: [1, 2, 3]
Explanation: All three values tie at frequency 2; the deterministic tie-break orders them by value ascending.
Input: ([0, 0, 0, 9, 9, 8, 8, 8, 8], 3)
Expected Output: [8, 0, 9]
Explanation: Frequencies: 8->4, 0->3, 9->2. Ordered by frequency descending gives [8, 0, 9].
Hints
- Every approach shares the same first step: count how often each value appears with a hash map in O(n) time.
- You never need to fully sort all distinct values when you only want the top k — a size-k min-heap selects them in O(n + d log k).
- No value can appear more than n times, so frequencies fall in [1, n]. Bucket the values by their count and scan from the highest bucket down for true O(n) time with no sort.