Choosing between BFS, DFS, Dijkstra and DP
“How do you decide between BFS, DFS, Dijkstra, and Dynamic Programming?”
What this tests
- Whether the candidate sees these as answers to different questions rather than interchangeable tools.
- Whether they know the precise precondition of each (unweighted, non-negative weights, acyclic subproblem graph).
- Whether they can recognize that DP is shortest path on a DAG, and BFS is Dijkstra with unit weights.
- Whether they can state complexity in terms of
VandE.
Strong answer
A strong candidate reframes the question: each of these answers a specific question about a specific kind of graph. What am I being asked — reachability, a shortest path, an ordering, an optimal value — and what does the graph look like — weighted or not, cyclic or not, explicit or implicit (states in a puzzle are a graph too).
Breadth-First Search (BFS) answers "fewest edges" and explores by distance layers; it is optimal only when every edge costs the same. Depth-First Search (DFS) answers structural questions — does a path exist, are there cycles, what is a topological order, which components exist — and is the natural backbone of backtracking. Dijkstra's Algorithm is BFS generalized to non-negative weights: replace the queue with a Priority Queue and you are done; its correctness argument breaks the moment a negative edge appears. Dynamic Programming is shortest (or best) path on a DAG: the subproblem dependency graph must be acyclic so subproblems can be solved in one topological pass.
The unifying view: all four are "process states in a valid order and relax transitions". BFS orders by hop count, Dijkstra by tentative distance, DP by topological order of subproblems, DFS by discovery. If the state graph has cycles and weights, you cannot use DP and need Dijkstra; if it is acyclic, DP is simpler and linear; if weights are uniform, BFS is both simpler and faster than Dijkstra.
Green flags · Red flags
- Asks "weighted or unweighted?" and "cyclic or acyclic?" before naming an algorithm.
- Describes Dijkstra as BFS with a priority queue and knows exactly why negative edges break it.
- Identifies DP as shortest path on a DAG and uses that to explain when DP is impossible.
- Recognizes implicit graphs: puzzle states, word transformations, grid cells.
- Gives complexities in
VandE, notn. - Mentions that BFS on unit weights beats Dijkstra in both simplicity and speed.
- Says "DFS finds the shortest path" without qualification.
- Proposes Dijkstra for an unweighted grid.
- Treats DP as unrelated to graphs, or cannot say what property the subproblem structure must have.
- Uses DFS with visited-set for shortest paths on unweighted graphs.
- Cannot explain why Dijkstra fails on negative weights beyond "it just does".
Follow-up questions
Each follow-up changes a requirement; the right answer changes with it.
k edges?