migrate 392 questions to pattern format

This commit is contained in:
2025-09-10 18:05:55 +01:00
parent fe59de3392
commit 0c43a4a95d
402 changed files with 1383 additions and 545 deletions

View File

@@ -9,7 +9,8 @@ categories:
- heap
- sorting
patterns:
- heap
- slug: counting-sort
is_optimal: true
function_signature: "def top_k_frequent(nums: list[int], k: int) -> list[int]:"
@@ -133,6 +134,27 @@ explanation:
time_complexity: "O(n). We make one pass to count frequencies and one pass to fill and traverse buckets."
space_complexity: "O(n). We use a hash map for counts and an array of buckets, both proportional to the input size."
pattern_comparison: |
**Bucket Sort vs Heap: Which Pattern Wins?**
Both patterns solve this problem correctly, but with different trade-offs:
| Approach | Time | Space | When to Use |
|----------|------|-------|-------------|
| **Bucket Sort** | O(n) | O(n) | When frequencies are bounded (always true here since max freq ≤ n) |
| **Min Heap** | O(n log k) | O(n) | When k is much smaller than n, or for streaming data |
| **Sorting** | O(n log n) | O(n) | Simplest to implement, but doesn't meet the follow-up requirement |
**Why Bucket Sort is optimal here:**
- Frequencies are naturally bounded by array length — if you have `n` elements, the maximum frequency is `n`
- This bounded range lets us use the frequency as a direct array index, avoiding comparison-based sorting entirely
- We achieve O(n) time by exploiting the problem's structure
**When to prefer Heap:**
- Streaming scenarios where you don't know all elements upfront
- When `k << n` (the O(log k) factor becomes negligible)
- When you need to support dynamic updates (adding/removing elements)
solutions:
- approach_name: Bucket Sort
is_optimal: true