QA
Beginner LevelData Structures & Algorithms

What is the difference between BFS and DFS graph traversal?

ā“ Interview Prompt: Compare Breadth-First Search (BFS) and Depth-First Search (DFS) — data structures used, space complexity, and use cases.

Both BFS and DFS traverse all reachable vertices in $O(V + E)$ time.

| Property | BFS | DFS |

|---|---|---|

| Data Structure | Queue | Stack (or recursion) |

| Space | $O(W)$ max width | $O(H)$ max height |

| Order | Level-by-level | Deep path first |

| Shortest Path | āœ… (unweighted) | āŒ |

| Cycle Detection | āœ… | āœ… |

| Topological Sort | āŒ | āœ… |

| Connected Components | āœ… | āœ… |

When to Use:

•
BFS: Shortest path (unweighted), social network proximity levels, word ladder.
•
DFS: Maze/puzzle solving, topological sort, strongly connected components.

Code Implementation Example

typescript
// BFS — shortest path in unweighted graph
function bfs(graph: Map<number, number[]>, start: number): Map<number, number> {
  const dist = new Map([[start, 0]]);
  const queue = [start];
  while (queue.length) {
    const node = queue.shift()!;
    for (const neighbor of graph.get(node) ?? []) {
      if (!dist.has(neighbor)) {
        dist.set(neighbor, dist.get(node)! + 1);
        queue.push(neighbor);
      }
    }
  }
  return dist;
}
šŸ’”BFS computing shortest distances from a source node.
šŸŽÆ Interview Key Takeaway

BFS uses a queue and finds shortest paths in unweighted graphs. DFS uses a stack and is ideal for topological sorting and cycle detection.

#DSA#BFS#DFS#Graphs#Traversal#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?