BFS and DFS: Your Two Traversal Tools
Every graph and tree problem in a coding interview boils down to one fundamental question: how do you visit every node? The answer is always one of two strategies — breadth-first search (BFS) or depth-first search (DFS). Understanding BFS vs DFS interview questions is not about memorizing two algorithms. It is about knowing which tool to reach for when you see a new problem.
Both BFS and DFS visit every reachable node exactly once. Both run in O(V + E) time for graphs and O(n) time for trees. The difference is the order they visit nodes, which determines what kind of questions each one answers efficiently. Pick the wrong traversal and you will either write a correct-but-slow solution or struggle with unnecessary complexity.
This guide gives you a clear decision framework. By the end, you will be able to read a problem statement and immediately know whether BFS or DFS is the right choice — and more importantly, why.
BFS Explained: Queue-Based, Level-by-Level Traversal
Breadth-first search explores nodes level by level, visiting all neighbors of the current node before moving deeper. It uses a queue (FIFO) as its core data structure. You start by enqueuing the source node, then repeatedly dequeue a node, process it, and enqueue all its unvisited neighbors.
The key property of BFS is that it guarantees the shortest path in unweighted graphs. When BFS first reaches a node, the path it took to get there is guaranteed to have the fewest edges. This is not true for DFS. If a problem asks for the minimum number of steps, minimum moves, or shortest distance in an unweighted graph, BFS is almost always the correct approach.
BFS uses O(V) space in the worst case, where V is the number of vertices — the queue can hold up to an entire level of nodes at once. For wide graphs or trees, this can be significant. In a complete binary tree, the last level alone contains roughly half of all nodes, so BFS on a balanced tree uses O(n/2) space.
The BFS template is straightforward: initialize a queue with the starting node, mark it as visited, and loop while the queue is not empty. Each iteration dequeues the front node, checks if it is the target, and enqueues all unvisited neighbors. For level-order problems, you process one full level per iteration by capturing the queue size at the start of each loop.
- Data structure: Queue (FIFO)
- Visit order: Level by level, closest nodes first
- Guarantees shortest path in unweighted graphs
- Space complexity: O(V) — can be large for wide graphs
- Time complexity: O(V + E) for graphs, O(n) for trees
Key Fact
BFS guarantees the shortest path in unweighted graphs — this is the single most important fact for choosing between BFS and DFS.
DFS Explained: Stack-Based, Depth-First Exploration
Depth-first search explores as far as possible along each branch before backtracking. It uses a stack (LIFO) — either explicitly or through the call stack via recursion. You start at the source node, pick one neighbor, go as deep as possible, then backtrack to explore the next branch.
DFS does not guarantee the shortest path. It finds a path, but not necessarily the optimal one. What DFS excels at is exhaustive exploration — it naturally fits problems where you need to explore all possibilities, detect cycles, find connected components, or generate permutations and combinations.
The space complexity of DFS is O(H) where H is the maximum depth of the search. For trees, this is O(log n) for balanced trees and O(n) for skewed trees. For graphs, it is O(V) in the worst case. In many practical scenarios, DFS uses less memory than BFS because it only stores nodes along the current path, not an entire level.
Recursive DFS is typically the shortest code to write in an interview. A simple function that marks a node as visited, processes it, and recursively calls itself on each unvisited neighbor is often fewer than 10 lines. This simplicity is a real advantage when you are coding under time pressure.
- Data structure: Stack (explicit) or call stack (recursion)
- Visit order: Deepest nodes first, backtracks when stuck
- Does NOT guarantee shortest path
- Space complexity: O(H) — height of the search tree
- Time complexity: O(V + E) for graphs, O(n) for trees
Side-by-Side Comparison: BFS vs DFS Interview Cheat Sheet
When comparing breadth first search vs depth first search, the differences become clear when you line them up. Both have the same time complexity, but they differ in space usage, traversal order, and the types of problems they solve best. This graph traversal comparison table is your quick reference for BFS DFS LeetCode problems.
The most important takeaway from this table is the "best for" row. BFS is your tool for shortest path and level-order problems. DFS is your tool for exhaustive search, cycle detection, and topological ordering. When either could work — such as counting connected components — DFS is often the simpler choice because recursive code is shorter.
- Time complexity: Both O(V + E) — identical performance
- Space complexity: BFS O(V) for wide graphs, DFS O(H) for deep graphs
- Data structure: BFS uses a queue, DFS uses a stack or recursion
- Shortest path: BFS guarantees it in unweighted graphs, DFS does not
- Best for BFS: Shortest path, level-order traversal, nearest neighbor
- Best for DFS: Path existence, cycle detection, topological sort, permutations
- When to avoid BFS: Very wide graphs where the queue grows too large
- When to avoid DFS: Shortest path problems, very deep or infinite graphs without depth limits
Pro Tip
When both BFS and DFS work, default to DFS — recursive DFS is shorter to code in an interview and easier to reason about for most tree problems.
When to Use BFS: Shortest Path and Level-Order Problems
BFS is the correct choice whenever the problem involves finding the shortest path, minimum steps, or closest target in an unweighted graph. The reason is fundamental: BFS explores nodes in order of their distance from the source. The first time BFS reaches any node, that path is guaranteed to be the shortest.
Level-order traversal is another BFS specialty. LeetCode #102 (Binary Tree Level Order Traversal) is the classic example — you need to return node values grouped by level, which maps directly to how BFS processes nodes. Any problem that asks you to process nodes "layer by layer" or "level by level" is a BFS problem.
Word Ladder (#127) is one of the most commonly asked BFS problems in interviews. You are given a start word and an end word, and you need to find the shortest transformation sequence where each step changes exactly one letter. Each word is a node, each single-letter change is an edge, and BFS finds the shortest chain. Trying to solve this with DFS would either give you a non-shortest path or require checking all possible paths — both unacceptable.
Nearest neighbor and multi-source BFS problems also demand breadth-first search. Rotting Oranges (#994) starts BFS from all rotten oranges simultaneously to find the minimum time to infect all fresh oranges. 01 Matrix (#542) finds the distance from each cell to the nearest zero. In these problems, BFS naturally radiates outward from sources, making the solution both correct and efficient.
- LeetCode #102 — Binary Tree Level Order Traversal (level-order grouping)
- LeetCode #127 — Word Ladder (shortest transformation sequence)
- LeetCode #994 — Rotting Oranges (multi-source minimum time)
- LeetCode #542 — 01 Matrix (nearest distance from each cell)
- LeetCode #752 — Open the Lock (minimum turns to reach target)
When to Use DFS: Exhaustive Search and Path Problems
DFS is the correct choice when you need to explore all possibilities, detect cycles, find any valid path, or perform topological sorting. The key insight for tree traversal BFS DFS decisions is this: if the problem asks "does a path exist" rather than "what is the shortest path," DFS is usually simpler and more natural.
Number of Islands (#200) is the quintessential DFS problem. You scan the grid, and when you find land, you use DFS to "sink" the entire island by marking all connected land cells as visited. Each DFS call handles one island. BFS would also work here, but recursive DFS is shorter to write and easier to reason about.
Course Schedule (#207) uses DFS for cycle detection in a directed graph. You model courses as nodes and prerequisites as edges, then check if the graph has a cycle — if it does, you cannot complete all courses. DFS with a three-color marking system (unvisited, in-progress, completed) detects back edges that indicate cycles. This pattern also powers topological sort, which orders nodes so that all dependencies come before dependents.
Backtracking problems — permutations, combinations, subsets, N-Queens — are inherently DFS. You explore one choice fully, backtrack, and try the next. The recursive call stack naturally maintains your current state. Trying to solve these with BFS would require explicitly managing all partial states in a queue, which is both more complex and more memory-intensive.
- LeetCode #200 — Number of Islands (connected component counting)
- LeetCode #207 — Course Schedule (cycle detection in directed graph)
- LeetCode #46 — Permutations (backtracking / exhaustive generation)
- LeetCode #98 — Validate Binary Search Tree (in-order DFS check)
- LeetCode #210 — Course Schedule II (topological sort via DFS)
Common Mistake
Using DFS for shortest-path problems is a common interview mistake — DFS finds A path, not THE shortest path. If the problem says "minimum steps" or "shortest", use BFS.
Quick Decision Framework: BFS or DFS in 10 Seconds
Here is the decision framework that will serve you in every BFS vs DFS interview question. Read the problem statement and ask yourself three questions in order. First: does the problem ask for the shortest path, minimum steps, or closest target? If yes, use BFS. This is the single most reliable signal.
Second: does the problem require exhaustive search — generating all permutations, detecting cycles, topological sorting, or exploring all paths? If yes, use DFS. The recursive structure maps naturally to these problems, and backtracking is trivially implemented with DFS.
Third: could either BFS or DFS work — for example, counting connected components, checking if a path exists, or traversing all nodes? In this case, default to DFS. Recursive DFS is shorter to write, easier to debug, and requires no queue setup. In a 45-minute interview, saving 2 minutes on boilerplate code is meaningful.
There are edge cases to be aware of. For very deep or infinite graphs, iterative DFS with an explicit stack is safer than recursion to avoid stack overflow. For problems on grids where the shortest path matters, BFS is non-negotiable. And for problems that ask for "all shortest paths" (not just one), you may need BFS combined with backtracking — but these are rare in interviews.
- 1Ask: "Does the problem mention shortest path, minimum steps, or closest?" — If yes, use BFS
- 2Ask: "Does the problem need exhaustive search, cycle detection, or topological sort?" — If yes, use DFS
- 3Ask: "Could either work?" — Default to DFS (recursive DFS is shorter to code in interviews)
- 4Edge case: Very deep graphs? Use iterative DFS with an explicit stack to avoid stack overflow
- 5Edge case: Grid shortest path? BFS is non-negotiable — DFS will not give the correct answer