DSAIntermediate6 min readPart 9 of 16

BFS vs DFS

BFS (breadth-first search) and DFS (depth-first search) are the two basic ways to walk a graph or tree. Picking the right one depends on the problem, and interviewers expect you to explain why.

Can you explain bfs vs dfs out loud?

I'm Alex. Read this, then I'll interview you on real problems and push on the parts you skip.

Same tree, two ordersCore idea

BFS: level by level4251637Visits 1, 2, 3, 4, 5, 6, 7: a whole level before thenext.DFS: one branch at a time4251637Visits 1, 2, 4, 5, 3, 6, 7: down to a leaf, then backup.
DiagramThe coloured nodes are the first three each search visits.

BFS explores every neighbour at the current distance before moving further out. It uses a queue, and in an unweighted graph the first time it reaches a node is along a shortest path.

BFS on an adjacency listTypeScript
function bfs(graph: Map<number, number[]>, start: number): number[] {
  const visited = new Set<number>();
  const queue = [start];
  const result: number[] = [];
  visited.add(start);
  while (queue.length) {
    const node = queue.shift()!;
    result.push(node);
    for (const neighbor of graph.get(node) || []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
  return result;
}
TimeO(V + E)SpaceO(V), a whole level can sit in the queue

DFS follows one path as far as it can, then backs up and tries the next. It uses a stack (usually the call stack, through recursion), and on wide graphs it uses less memory than BFS.

DFS, recursiveTypeScript
function dfs(graph: Map<number, number[]>, start: number): number[] {
  const visited = new Set<number>();
  const result: number[] = [];
  function explore(node: number) {
    visited.add(node);
    result.push(node);
    for (const neighbor of graph.get(node) || []) {
      if (!visited.has(neighbor)) explore(neighbor);
    }
  }
  explore(start);
  return result;
}
TimeO(V + E)SpaceO(height), the recursion stack

When to use whichCompare

ScenarioUseWhy
Shortest path (unweighted)BFSIt goes level by level, so the first time you reach the target is the shortest path.
Does a path exist?EitherBoth can tell whether two nodes are connected.
Visit every nodeEitherBoth visit everything.
Topological sortDFSThe post-order of a DFS gives a valid order naturally.
Detect a cycleDFSDFS spots a back edge using the current recursion path.
Level-order traversalBFSBFS processes a tree one level at a time.
Tight on memoryDFSDFS uses O(height) space; BFS uses O(width).

Common mistakesPitfalls

Using BFS for topological sort without knowing Kahn’s algorithmBFS works (Kahn’s algorithm), but DFS is more natural and more often expected.
Using DFS for shortest pathDFS does not guarantee the shortest path in an unweighted graph.
Forgetting the visited setWithout it, both BFS and DFS loop forever on a cycle.
Confusing BFS with level-orderBFS is the algorithm; level-order is one use of it on trees.
Not handling disconnected partsLoop over every node and start a new search from each unvisited one.

In the interviewIn the interview

Frequently asked questionsFAQ

When should you use BFS instead of DFS?

Use BFS when you need the shortest path in terms of edge count on a uniform-weight graph, or level-by-level processing such as printing a tree by rows. BFS visits nodes in order of distance from the source, so the first time you reach a target guarantees the minimum number of edges.

Why is DFS preferred for cycle detection in directed graphs?

DFS keeps a stack of the current recursion path, so it can detect a back edge pointing to an ancestor, which signals a cycle in a directed graph. Kahn's algorithm using BFS and in-degree counts also works. DFS is simpler when the graph is already traversal-oriented.

What is the time complexity of BFS and DFS?

Both visit every vertex and edge once in the worst case, giving O(V + E) time with an adjacency list and O(V^2) with an adjacency matrix. Space is O(V) for the visited set plus the queue for BFS or the recursion stack for DFS.

Now explain bfs vs dfs to me out loud

I'll give you interview problems and ask follow-ups, like a real interviewer.

Practice with Alex

Keep readingKeep reading

Ready to practice?

Reading is step one. Saying it out loud is step two.

Start a mock interview with Alex, get pushed on the parts you skip, and see your hiring signal right after.