Blog

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

© 2025 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);
      }
    }
  }
}

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