DSA Interview Question

What is the difference between BFS and DFS?

Updated 2026-07-10 · Beginner friendly
Quick answer

Breadth first search explores a graph level by level using a queue, so it visits all near nodes before far ones and finds the shortest path in an unweighted graph. Depth first search goes as deep as possible down one path using a stack or recursion before backtracking. BFS suits shortest path problems, while DFS suits exploring all paths, cycle detection, and topological sorting.

Breadth first search

It uses a queue and spreads out evenly. Because it reaches nodes in order of distance, it naturally finds the shortest number of steps in an unweighted graph.

Depth first search

It uses a stack, often through recursion, and dives deep down one branch before trying others. It is great when you need to explore every path or detect cycles.

# BFS uses a queue
from collections import deque
def bfs(graph, start):
    seen, q = {start}, deque([start])
    while q:
        node = q.popleft()
        for nb in graph[node]:
            if nb not in seen:
                seen.add(nb)
                q.append(nb)
In the interview

The one line that lands well is BFS for shortest path in an unweighted graph, DFS for exploring all paths and detecting cycles. Adding that BFS uses a queue and DFS uses a stack ties it together.

Want the full DSA guide?

Read every DSA concept with notes, diagrams, and code in one place. Track your progress as you go.

Open the DSA guide All DSA questions