Graphs = nodes + connections. Friends networks, city maps, course prerequisites, the web itself. Product companies ask them; service companies rarely โ prioritize accordingly.
Representing one
// adjacency list โ the standard
const graph = {
A: ["B", "C"],
B: ["D"],
C: ["D"],
D: []
};BFS โ explore level by level (queue)
function bfs(start) {
const queue = [start], seen = new Set([start]);
while (queue.length) {
const node = queue.shift();
for (const next of graph[node])
if (!seen.has(next)) { seen.add(next); queue.push(next); }
}
}
// BFS finds SHORTEST path in unweighted graphs โ that's its superpowerDFS โ go deep first (recursion/stack)
function dfs(node, seen = new Set()) {
seen.add(node);
for (const next of graph[node])
if (!seen.has(next)) dfs(next, seen);
}The three classics
- Number of Islands: DFS-flood each unvisited land cell in a grid
- Shortest path (unweighted): BFS with distance tracking
- Cycle detection: DFS with a "currently visiting" set
The seen set is non-negotiable โ without it, any cycle = infinite loop.