Skip to the solution
MediumDSA10 min read

When would you use BFS over Dijkstra for shortest paths?

647 views

The problem

Question presented to candidate: "You need shortest paths in a graph. When is a plain BFS enough, and when do you need Dijkstra? Show me both in Python and explain what goes wrong if you pick the wrong one."

What a strong answer should cover:

  • BFS minimises the number of edges; Dijkstra minimises total weight. They agree exactly when all weights are equal (any equal value, not only 1).
  • Why BFS is correct there: its FIFO queue already releases nodes in distance order, so the O(log V) heap is unnecessary.
  • A concrete counterexample where BFS picks a fewer-edge but more expensive path.
  • 0-1 BFS with a deque for weights 0 and 1, and Bellman-Ford when weights can be negative.
  • Python specifics: collections.deque with popleft() (O(1)) instead of list.pop(0), and heapq for Dijkstra.

Code / implementation expected: Yes โ€” a Python BFS with collections.deque and a Dijkstra with heapq, ideally plus 0-1 BFS with appendleft.

  • graphs
  • shortest-path

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

10 min read ยท 12 sections

Python code

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

PythonBFS and Dijkstra on equal and unequal weights
Python0-1 BFS with a deque versus Dijkstra

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 75 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 do a level-order (BFS) traversal of a tree?

Continue