Depth-First Search
O(V + E) time, O(h) to O(V) space (stack/recursion)
Use When
- Need full path exploration, recursion, or subtree aggregation
- Memory should scale by depth instead of breadth
- Backtracking-style state is part of the solution
Avoid When
- You must guarantee shortest path in unweighted graph
- You need strict level-by-level processing
Mental model: Go deep, then backtrack.
Breadth-First Search
O(V + E) time, O(w) to O(V) space (queue width)
Use When
- Need shortest path / minimum steps in unweighted graph
- Level-order processing or multi-source expansion
- Distance from source matters directly
Avoid When
- Graph is very wide and memory is tight
- Only subtree/path aggregation is needed
Mental model: Expand in waves from the source.