Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmseasy

BFS vs DFS — what’s the difference and when to use which?

Tags
#bfs#dfs#graph#traversal
Back to categoryPractice quiz

Answer

BFS explores level by level and finds the shortest path in an unweighted graph. DFS goes deep first and is handy for traversals, cycle detection, and topological-style problems.

function bfs(start: number, graph: number[][]) {
  const q: number[] = [start];
  const seen = new Set<number>([start]);

  while (q.length) {
    const v = q.shift()!;
    for (const n of graph[v]) {
      if (!seen.has(n)) {
        seen.add(n);
        q.push(n);
      }
    }
  }
}

Advanced answer

Deep dive

Both algorithms visit each vertex/edge at most a constant number of times, so the baseline time is O(V+E). The difference is order and the data structure.

  • BFS uses a queue and explores in increasing distance (layers). That’s why it gives shortest paths in unweighted graphs.
  • DFS uses a stack (often recursion) and explores as deep as possible; it’s great for entry/exit ordering.

When to use which

  • BFS: shortest path by number of edges, level order, bipartite check, minimum moves.
  • DFS: cycle detection (directed graphs), topological reasoning, connected components, backtracking.

Practical notes

  • In JS, `shift()` makes BFS slow; prefer an index-based queue.
  • DFS recursion can overflow on deep graphs; use an explicit stack when needed.

Related questions

Algorithms
What is a topological sort and when is it possible?
#topological-sort#dag#graph
Algorithms
When can BFS replace Dijkstra’s algorithm?
#shortest-path#bfs#dijkstra
Algorithms
What is Dijkstra's Algorithm?
#graph#shortest-path
#dijkstra
Algorithms
BFS vs DFS?
#graph#bfs#dfs
Data Structures
Adjacency list vs adjacency matrix: when do you choose each?
#graph#adjacency-list#adjacency-matrix