Top k elements Flashcards
(5 cards)
What is the pattern and when is it used for Top K Elements?
Uses heap or sorting to find top k elements.
Use Case: Frequent elements, kth largest.
Example: [No LeetCode match, course example: Top K Frequent Elements]. Action: Verbalize use case aloud.
What are the key steps for Top K Elements?
- Count element frequencies.
- Use min heap of size k for top elements.
- Extract top k.
Action: Explain steps for Top K Frequent Elements aloud.
How does Top K Elements apply to Top K Frequent Elements?
Find k most frequent elements. Count frequencies, use min heap to keep top k.
Example: Top K Frequent Elements.
Action: Verbalize solution logic aloud.
What are the complexity and gotchas for Top K Elements?
Time: O(n log k), Space: O(n).
Gotchas: Ties in frequency, k > n.
Action: List edge cases for Top K Frequent Elements aloud.
Code example for Top K Elements.
```python
from typing import List
from collections import Counter
from heapq import heappush, heappop
def top_k_frequent(nums: List[int], k: int) -> List[int]:
counts = Counter(nums)
heap: List[tuple[int, int]] = []
for num, freq in counts.items():
heappush(heap, (freq, num))
if len(heap) > k:
heappop(heap)
return [num for _, num in heap]
~~~