Graph (DFS & BFS)
Graph problems involve nodes (vertices) connected by edges. Depth-First Search (DFS) and Breadth-First Search (BFS) are fundamental algorithms for graph traversal, each with specific use cases.Key Concepts
Graph Representations
- Adjacency List:
graph[node] = [neighbors]- O(V+E) space, efficient - Adjacency Matrix:
matrix[i][j] = edge- O(V²) space, fast lookup - Edge List: List of (u, v) pairs - O(E) space, simple
DFS vs BFS
| Aspect | DFS | BFS |
|---|---|---|
| Data Structure | Stack (recursion) | Queue |
| Path | Not shortest | Shortest (unweighted) |
| Memory | O(h) depth | O(w) width |
| Use Case | Connectivity, cycles | Shortest path, levels |
Key Patterns & Techniques
1. DFS Patterns
- Connectivity: Find connected components
- Cycle Detection: Track visited nodes in current path
- Backtracking: Explore all paths, undo choices
- Topological Sort: Post-order DFS
2. BFS Patterns
- Shortest Path: Level-by-level in unweighted graphs
- Level Order: Process nodes at same distance
- Multi-source BFS: Start from multiple sources
3. Union-Find (Disjoint Set)
- Find connected components
- Detect cycles
- O(α(n)) amortized per operation
4. Topological Sort
- Order nodes in DAG (Directed Acyclic Graph)
- Used in dependency resolution
- DFS or Kahn’s algorithm (BFS)
Common Approaches
DFS Template (Recursive)
DFS Template (Iterative)
BFS Template
Clone Graph (DFS)
Topological Sort (Kahn’s Algorithm)
Problems in This Category
025. Clone Graph
Medium | Frequency: 71.4%DFS with hash map to track original to clone mapping.
063. Course Schedule
Medium | Frequency: 47.0%Detect cycle in directed graph using DFS or topological sort.
031. Shortest Path in Binary Matrix
Medium | Frequency: 67.4%BFS on grid for shortest path with 8-directional movement.
038. Accounts Merge
Medium | Frequency: 62.4%Union-Find or DFS to merge connected email accounts.
055. Subsets
Medium | Frequency: 47.0%Backtracking DFS to generate all possible subsets.
081. Word Ladder
Hard | Frequency: 40.7%BFS for shortest transformation sequence between words.
053. Robot Room Cleaner
Hard | Frequency: 51.9%DFS with backtracking to explore unknown grid.
070. Swim in Rising Water
Hard | Frequency: 40.7%Binary search + BFS or Dijkstra’s for minimum time path.
036. Making A Large Island
Hard | Frequency: 65.0%DFS to find component sizes, try flipping each 0.
086. Shortest Path in Hidden Grid
Medium | Frequency: 32.0%DFS to discover grid, then BFS for shortest path.
Complexity Characteristics
| Pattern | Time Complexity | Space Complexity | When to Use |
|---|---|---|---|
| DFS | O(V + E) | O(V) | Connectivity, cycles, paths |
| BFS | O(V + E) | O(V) | Shortest path, levels |
| Union-Find | O(E * α(V)) | O(V) | Dynamic connectivity |
| Topological Sort | O(V + E) | O(V) | Task scheduling, dependencies |
| Dijkstra | O((V+E) log V) | O(V) | Weighted shortest path |
Interview Tips
Pattern Recognition
- “Connected components” → DFS or Union-Find
- “Shortest path” (unweighted) → BFS
- “Detect cycle” → DFS with recursion stack or Union-Find
- “All paths/combinations” → DFS with backtracking
- “Task scheduling/dependencies” → Topological sort
- “Grid with obstacles” → BFS for shortest path
- “Weighted shortest path” → Dijkstra or Bellman-Ford
Common Mistakes
- Forgetting to mark visited before adding to queue (BFS)
- Not unmarking visited in backtracking problems
- Confusing directed vs undirected graphs
- Stack overflow in DFS on large graphs (use iterative)
- Not handling disconnected graphs (multiple components)
Key Insights
- DFS = Exploration - go deep, good for exhaustive search
- BFS = Level-order - guarantees shortest path in unweighted graphs
- Visited set is crucial - prevents infinite loops in cycles
- Grid = Implicit graph - cells are nodes, adjacency is edges
- Multi-source BFS - add all sources to queue initially
- Backtracking - mark visited on enter, unmark on exit
Grid as Graph
Advanced Patterns
Union-Find (Disjoint Set)
Bidirectional BFS
Pro Tip: BFS guarantees shortest path in unweighted graphs. Use it for “minimum steps” problems. DFS is simpler for connectivity and uses less memory. For weighted graphs, use Dijkstra’s algorithm.