Graphs, BFS and DFS
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Represent a graph with an adjacency list and explain the trade-off against a matrix.
- Traverse a graph with breadth-first and depth-first search.
- Use a visited set to avoid revisiting nodes and infinite loops.
Overview
#Vertices and edges
A graph is a set of vertices connected by edges. Edges can be directed or undirected and can carry weights. Unlike a tree, a graph can contain cycles and disconnected components.
Two representations
An adjacency list stores, for each vertex, the list of its neighbours. Space is O(vertices + edges), which is efficient for sparse graphs. An adjacency matrix stores a grid of booleans, using O(vertices^2) space but giving O(1) edge lookup. Choose the list for most interview problems and the matrix when edges are dense or lookups dominate.
Breadth-first search
BFS explores by increasing distance from the start using a queue:
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
while (queue.length) {
const node = queue.shift();
order.push(node);
for (const next of graph[node] || []) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next);
}
}
}
return order;
}
Mark a node visited when you enqueue it, not when you dequeue it, or the queue can hold duplicates.
Depth-first search
DFS follows one path as far as possible before backtracking, using recursion or an explicit stack. It is natural for exploring all paths, detecting cycles and computing connected components.
Complexity
Both traversals visit each vertex once and examine each edge once, so both are O(vertices + edges) time. The visited set costs O(vertices) space.
Grids are graphs
A grid is a graph where each cell is a vertex and its neighbours are the cells above, below, left and right. Flood fill and island counting are BFS or DFS over a grid.
Practice next
- Count the number of connected components in an undirected graph.
- Find the shortest path length in an unweighted graph with BFS.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Starting BFS at 1 in the graph 1-2, 1-3, 2-4, what order are vertices visited?
starter.javascript// queue starts with 1Reveal the reference answer
reference.javascriptVisit 1, enqueue 2 and 3. Visit 2, enqueue 4. Visit 3. Visit 4. The order is [1, 2, 3, 4].Authored expected output: [1, 2, 3, 4]
BFS visits all neighbours of a node before moving deeper.
Exercise 2Debug
This BFS can enqueue the same node several times. Find the bug.
starter.javascriptwhile (queue.length) { const node = queue.shift(); if (visited.has(node)) continue; visited.add(node); for (const next of graph[node]) queue.push(next); }Reveal the reference answer
reference.javascriptwhile (queue.length) { const node = queue.shift(); if (visited.has(node)) continue; visited.add(node); for (const next of graph[node]) { if (!visited.has(next)) queue.push(next); } }Authored expected output: Each node enqueued at most once
Checking visited before pushing prevents duplicate queue entries and wasted work.
Exercise 3Explain
Explain why BFS finds the shortest path in an unweighted graph but not in a weighted one.
Reveal the reference answer
reference.textIn an unweighted graph every edge costs the same, so the first time BFS reaches a node it has used the fewest edges, which is the shortest path. In a weighted graph a path with more edges can be cheaper, so BFS can reach a node by an expensive route first. Weighted shortest paths need algorithms such as Dijkstra.Authored expected output: Equal edge costs make fewest-edges optimal; weights break that assumption.
BFS optimises edge count, not total weight.
Common misconceptions
#- A tree traversal algorithm works on any graph. Graphs can revisit nodes, so a visited set is required.
- Marking visited on dequeue is fine. It can enqueue the same node many times; mark on enqueue.
- BFS and DFS differ in complexity. Both are O(vertices + edges); they differ in order and use cases.
Follow-up practice
#- dsa-from-zero-topological-sort
- dsa-from-zero-shortest-paths
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.