Find top-k distinct elements
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of algorithms and data structures for selecting distinct top-k values and enforcing ordering constraints. It is commonly asked in coding and algorithms interviews to assess practical application skills in handling duplicates, ordering, and performance optimization, reflecting a practical algorithmic application rather than purely conceptual reasoning.
Constraints
- 1 <= len(nums) <= 10^5
- 1 <= k <= len(nums)
- -10^9 <= nums[i] <= 10^9
Examples
Input: ([5, 2, 2, 9, 1, 9, 7], 3)
Expected Output: [9, 7, 5]
Explanation: The distinct values are [5, 2, 9, 1, 7]. The 3 largest are 9, 7, and 5.
Input: ([4, 4, 4, 4], 2)
Expected Output: [4]
Explanation: There is only one distinct value, so return all distinct values.
Input: ([-1, -5, -3, -1, -2], 2)
Expected Output: [-1, -2]
Explanation: The distinct values are [-1, -5, -3, -2]. The 2 largest are -1 and -2.
Input: ([10], 1)
Expected Output: [10]
Explanation: A single-element array has exactly one distinct value.
Input: ([8, 6, 8, 7, 6, 5], 10)
Expected Output: [8, 7, 6, 5]
Explanation: There are only 4 distinct values, so return all of them in descending order.
Input: ([3, 1, 2, 2, 3], 3)
Expected Output: [3, 2, 1]
Explanation: The distinct values are [3, 1, 2], and all 3 should be returned in descending order.
Hints
- You only care about distinct values, so think about how to skip duplicates efficiently.
- A min-heap of size k can keep track of the current k largest distinct values without sorting everything.