Graph
Example
function dfs(graph, node) {
for (const next of graph.get(node)) {
dfs(graph, next);
}
}function dfs(graph, node, visited = new Set()) {
visited.add(node);
for (const next of graph.get(node)) {
if (!visited.has(next)) dfs(graph, next, visited);
}
return visited;
}Without a visited set, any cycle makes the recursion run until the stack overflows.
Common mistakes
- DFS on a cyclic graph that never ends because nothing tracks visited nodes.
- Adding an undirected edge in only one direction.
Key points
- Traversals keep a
visitedset so cycles do not cause infinite loops. - Sparse graphs use an adjacency list, such as a
Mapof arrays, not an n×n matrix. - Undirected edges are added in both directions.
Interview questions
Adjacency list vs adjacency matrix: which should I use?
An adjacency list uses O(V + E) space and suits sparse graphs. A matrix uses O(V²) space but checks whether an edge exists in O(1).
What is the time complexity of BFS and DFS on a graph?
Both are O(V + E) with an adjacency list, because each vertex and edge is processed once. With a matrix they are O(V²).
Directed vs undirected graph: what is the difference?
In a directed graph each edge goes one way, like a link from page A to page B. In an undirected graph each edge works both ways, like a friendship.