Skip to content
Preptima
mediumCodingConceptMidSeniorStaff

How do you decide between BFS and DFS - and how do you recognise a graph problem that nobody described as a graph?

Choose BFS when the question asks for the fewest steps in an unweighted graph or when you need results in distance order; choose DFS when you are asking a structural question such as connectivity, cycles or topological order, or when the graph is deep and narrow.

4 min readUpdated 2026-08-15

Answer

Short answer

Use BFS for the fewest steps in an unweighted graph or when results must come back in distance order. Use DFS for structural questions such as connectivity, cycles or topological order, or when the graph is deep and narrow.

Keep graphs explicit in the answer because that is the concept the interviewer is actually trying to test. A good graphs explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use graphs once more at the decision point so the answer reads as judgement rather than a detached example.

Keep graphs explicit in the answer because that is the concept the interviewer is actually trying to test. A good graphs explanation names the trade-off, the failure mode, and the evidence you would use before choosing.

Was this answer helpful?

Likely follow-ups

  • The edges now have weights of 0 or 1. What is the cheapest change to your BFS?
  • How would you detect a cycle in a directed graph, and why is the undirected version different?
  • Your DFS overflows the stack on a graph with a million nodes. What do you do?
  • Give me a problem you have seen that was a graph problem in disguise, and name its nodes and edges.

Related questions

Related Topics