Graph Algorithms & TraversalsAdvanced LevelStudy Time: 30 mins

BFS & DFS Algorithm

Breadth-First Search (BFS) explores graph nodes level-by-level using a Queue. Depth-First Search (DFS) explores as deep as possible along each branch using a Stack or Recursion.

Loading visualizer workspace...

Real-world analogy: Ripples vs Shaft Explorer

BFS
DFS
Hover over items for details

BFS is like ripples expanding outward in water (level by level). DFS is like a cave explorer walking down a tunnel to the bottom before backtracking.

  • BFS= Uses Queue (FIFO) for shortest path in unweighted graphs.
  • DFS= Uses Stack / Recursion (LIFO) for pathfinding and cycle detection.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapBFS & DFS: O((V + E) log V) Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)BFS & DFS Graph
Time Steps (N=500)

~4,483 steps (Linearithmic)

O((V + E) log V) Time

Space Footprint

O(V + E) Graph Memory

Memory growth rate as N expands.

Performance Rank
Moderate Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
BFS Time & SpaceO(V + E)O(V)
DFS Time & SpaceO(V + E)O(V)

Code implementations

function bfs(graph, start) {
  const visited = new Set([start]);
  const queue = [start];
  while (queue.length > 0) {
    const node = queue.shift();
    for (const neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
}

Real-world applications

Case 01

Social Recommendations

Finds 1st and 2nd degree friends.

Case 02

Web Crawlers

Discovers URL links level by level.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Bfs Dfs Knowledge & Skill Test

Validate your conceptual understanding, operation mechanics, and core concepts of Bfs Dfs.