Skip to the solution
MediumDSA14 min read

What is the difference between BFS and DFS?

525 views

The problem

Question presented to candidate: "Explain the difference between breadth-first search and depth-first search on a graph. Then implement both in Python and tell me when you would choose one over the other."

What a strong answer should cover:

  • The one structural difference: BFS uses a FIFO queue, DFS uses a LIFO stack (or recursion).
  • Visit order: BFS goes level by level, DFS goes deep then backtracks; both need a visited set for cycles.
  • Both are O(V + E) time; memory is the widest level for BFS and the deepest path for DFS.
  • BFS gives shortest paths in unweighted graphs; DFS does not. Typical uses of each (topological sort, cycle detection, backtracking vs nearest/minimum steps).
  • Python details: collections.deque with popleft() (not list.pop(0)), and the default recursion limit of 1000 that breaks recursive DFS on deep graphs.

Code / implementation expected: Yes โ€” BFS with deque and DFS both recursively and with a list used as a stack, in Python.

  • graphs
  • bfs
  • dfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBFS order and distances vs recursive and stack-based DFS
PythonBFS vs DFS paths, and queue size vs stack depth on three graph shapes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 85 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the maximum product subarray?

Continue