Top k elements Flashcards

(5 cards)

1
Q

What is the pattern and when is it used for Top K Elements?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps for Top K Elements?

A
  1. Count element frequencies.
  2. Use min heap of size k for top elements.
  3. Extract top k.

Action: Explain steps for Top K Frequent Elements aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does Top K Elements apply to Top K Frequent Elements?

A

Find k most frequent elements. Count frequencies, use min heap to keep top k.

Example: Top K Frequent Elements.

Action: Verbalize solution logic aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas for Top K Elements?

A

Time: O(n log k), Space: O(n).

Gotchas: Ties in frequency, k > n.

Action: List edge cases for Top K Frequent Elements aloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for Top K Elements.

A

```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]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly