Visit Every Neighbor Once

A graph is a set of things, called nodes, and the connections between them, called edges. A tree is a graph with strict rules: one root, one parent per node, and no way to loop back. Drop those rules and you get the data behind a lot of web apps. Packages depend on packages, services call services, users follow users, and the tiles of a game map touch their neighbors.

Edges can be one-way, like “app imports router”, or mutual, like a connection between two people. Ask which one you have before you write any code, because a mutual edge has to be stored in both directions.

Store Neighbors in a Map

Interview problems usually hand you a list of edges. Turn it into an adjacency list first, so you can ask for a node’s neighbors directly. A Map from each node to an array of its neighbors works well:

Language: JavaScript
const deps = [
  ["app", "router"],
  ["app", "ui"],
  ["ui", "icons"],
  ["router", "icons"],
];

const graph = new Map();
for (const [pkg, dep] of deps) {
  if (!graph.has(pkg)) graph.set(pkg, []);
  graph.get(pkg).push(dep);
}
console.log(graph.get("app"), graph.get("icons") ?? []);

The app package has two direct dependencies, and icons depends on nothing:

Language: Program Output
[ 'router', 'ui' ] []

A plain object looks like it would do the same job, but its keys share a namespace with Object.prototype. A package named constructor would find an inherited function instead of undefined, and graph[pkg] ??= [] would leave that function in place. A Map only knows the keys you put in it.

Remember Where You’ve Been

Unlike a tree, a graph can lead you back to a node you’ve already seen: icons above is reachable through two different packages, and a cycle could send a walk around forever. So every graph walk keeps a Set of visited nodes and skips anything already in it. That’s what makes the walk O(V + E): each node is handled once, and each edge is looked at once.

A depth-first walk follows one path as far as it goes before it backs up, and it answers questions about reaching something, such as “Does app pull in icons at all?” A recursive version reads well, but a long chain of nodes can exhaust the call stack, so an array used as a stack is the safer default.

Looking for a cycle in one-way edges needs one more distinction: reaching a node you’ve already finished is harmless, but reaching one that’s still on your current path means you’ve gone in a circle.

Level by Level for Distance

When the question is about the fewest steps, walk the graph breadth-first. Everything one step away comes first, then everything two steps away, and so on, so the first time you reach a node is along a shortest path.

That needs a queue, and shift() is the trap. Once an array holds more than a few thousand items, V8 moves every remaining item each time you remove the first one. Keep a head index instead and let the array grow:

Language: JavaScript
const follows = new Map([
  ["ada", ["bo", "cy"]],
  ["bo", ["dee"]],
  ["cy", ["dee"]],
  ["dee", []],
]);

const distance = new Map([["ada", 0]]);
const queue = ["ada"];
for (let head = 0; head < queue.length; head++) {
  const user = queue[head];
  for (const next of follows.get(user)) {
    if (distance.has(next)) continue;
    distance.set(next, distance.get(user) + 1);
    queue.push(next);
  }
}
console.log(distance);

The distance map doubles as the visited set, and it’s filled in when a node joins the queue, not when it leaves it:

Language: Program Output
Map(4) { 'ada' => 0, 'bo' => 1, 'cy' => 1, 'dee' => 2 }

Marking a node when you enqueue it keeps dee from going into the queue twice. Mark it later and a busy node can be queued once per neighbor.

Grids Are Graphs Too

A grid is a graph where every cell’s neighbors are the cells above, below, left, and right. You don’t need to build an adjacency list. Compute the neighbors with a list of offsets and skip anything outside the grid.

The JavaScript detail is the visited set. Arrays are compared by reference, so seen.has([2, 3]) is false even right after seen.add([2, 3]). Use a string key such as `${row},${col}`, a single number like row * width + col, or an array of booleans with one entry per cell.

In this section, you’ll check whether one package pulls in another, fill a region of pixels, find the fewest moves through a game map, catch a circular import, and review an AI-written function that measures how far apart two people are. For each one, decide first whether the question is about reaching something or about distance.

Become a Member to join the conversation.