BFS, DFS, And Shortest Path Search
Asked of: Software Engineer
Last updated

What's being tested
Demonstrate graph traversal skills: model grids/structures as graphs, pick the right search (unweighted vs weighted), and implement correct distance/reachability. Interviewers probe correct state representation, complexity reasoning, and edge-case handling like obstacles, multiple sources, and cycles.
Patterns & templates
-
BFS on unweighted graphs/grids — use
deque,visited, andparentmap; distances inO(V+E)time andO(V)space. -
Multi-source BFS — enqueue all sources with distance 0 to compute nearest-source distances in one pass.
-
Dijkstra for non-negative weights — use
priority_queue(min-heap); complexityO((V+E) log V). -
0-1 BFS when weights are 0/1 — use
dequeto getO(V+E)time without a heap. -
A* heuristic search — admissible heuristic (e.g., Manhattan) to speed grid shortest-paths while preserving optimality.
-
State representation — encode position and extra state (keys, direction) as tuples/ints; canonicalize to avoid duplicates.
-
Path reconstruction — store
parent[node]during search; reconstruct by backtracking to avoid re-traversal costs.
Common pitfalls
Pitfall: Treating a grid cell as visited before considering better paths — in weighted graphs you must allow distance relaxation (use Dijkstra).
Pitfall: Forgetting diagonal vs orthogonal neighbor rules — clarify movement model and neighbor generation deltas.
Pitfall: Not bounding memory for large N — represent visited compactly (
bitset/flattened index) for big grids.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
- Find the Shortest Click Path with a Fallible Link APISnowflake · Software Engineer · Technical Screen · medium
- Solve Array Distance and Wiki NavigationSnowflake · Software Engineer · Online Assessment · medium
- Find Shortest Wiki Click PathSnowflake · Software Engineer · Technical Screen · medium
- Find Shortest Grid PathSnowflake · Software Engineer · Technical Screen · medium
- Compute nearest bathroom distance for each deskSnowflake · Software Engineer · Technical Screen · hard
- Implement crawler and bracket validatorSnowflake · Software Engineer · Onsite · medium
- Find first error and propagate failuresSnowflake · Software Engineer · Technical Screen · medium
- Design error detection and propagation algorithmsSnowflake · Software Engineer · Technical Screen · medium
- Design a concurrent web crawlerSnowflake · Software Engineer · Onsite · hard
Related concepts
- DFS/BFS Tree, Graph, And Grid TraversalCoding & Algorithms
- BFS/DFS Graph and Tree Traversal and Shortest PathsCoding & Algorithms
- Graph Traversal And Shortest PathsCoding & Algorithms
- Graph, Grid, BFS/DFS, And Union-FindCoding & Algorithms
- BFS, DFS, Graph, And Grid TraversalCoding & Algorithms
- Shortest Path And Graph TraversalCoding & Algorithms