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

@@ -7,8 +7,10 @@ categories:
- graphs
- heap
patterns:
- bfs
- heap
- slug: heap
is_optimal: true
- slug: bfs
is_optimal: false
function_signature: "def network_delay_time(times: list[list[int]], n: int, k: int) -> int:"
@@ -146,6 +148,30 @@ explanation:
time_complexity: "O((V + E) log V). Each node is processed once, and each edge triggers at most one heap operation. With `n` nodes and `m` edges, this is O((n + m) log n)."
space_complexity: "O(V + E). We store the adjacency list (O(E)) and the distance dictionary plus heap (O(V))."
pattern_comparison: |
**Dijkstra (Heap) vs BFS: When Weights Matter**
This problem illustrates a critical distinction in graph traversal:
| Algorithm | Time | Works With | Use When |
|-----------|------|------------|----------|
| **Dijkstra (Heap)** | O((V+E) log V) | Non-negative weighted edges | Edge weights vary |
| **BFS** | O(V + E) | Unweighted or unit-weight edges | All edges have same cost |
| **Bellman-Ford** | O(V × E) | Any weights (including negative) | Negative edges possible |
**Why BFS fails here:**
BFS explores nodes in order of *hop count* (number of edges), not *total distance*. Consider:
```
A --1--> B --1--> C
A --------10------> C
```
BFS would reach C via the direct edge first (1 hop) with cost 10, missing the shorter 2-hop path with cost 2.
**Why Dijkstra works:**
The min-heap ensures we process nodes in order of *actual distance* from the source. When we first reach a node, we've found the shortest path to it (because all unvisited nodes are at least as far away).
**The key insight:** Dijkstra is essentially "weighted BFS" — the heap replaces the queue to account for edge weights.
solutions:
- approach_name: Dijkstra's Algorithm
is_optimal: true