skip to content

Graphs & Traversal

Graphs model networks of relationships — roads between cities, dependencies between tasks, links between people. Interviewers lean on them heavily because one modeling skill unlocks traversal, connectivity, ordering, and shortest-path questions alike.

part ofData structures & algorithmsoverview, primer and where to startread it →
on this pageshow

explore

questions

page 1 of 2

Why doesn't a minimum spanning tree give the cheapest route between two given nodes?

level: juniorimportance: must knowfreq 62%

answer

  1. One global sum, or many pairwise distances?
  2. What exactly does 'minimum' attach to?
  3. Try a three-node triangle with weights
  4. MST may omit a cheap direct edge
  5. Tree path minimizes heaviest edge, not total

basics

~20 s

A minimum spanning tree minimizes one global sum: the total weight of the edges keeping every node connected. It promises nothing about any specific pair, so its path between two nodes can cost more than a direct link.

solid answer

~40 s

The two structures optimize different things. A minimum spanning tree (MST) minimizes one number: the sum of the weights of the `V-1` edges that keep all `V` nodes connected. A shortest-path tree minimizes a different quantity — the distance from one chosen source to every other node, separately. Take three offices with trench costs A-B = 3, A-C = 2, B-C = 2. The MST takes the two cheapest links, A-C and B-C, for a total of 4; the A-to-B route inside that tree costs 4, while the direct A-B trench costs only 3, and the MST simply left it out. So an MST is the right answer to "cable every office for the least total money" and the wrong answer to "what is the fastest path from A to B".

go deeper

for a junior

Be ready to say in one breath that an MST minimizes total connection cost, not the cost between a chosen pair, and to sketch a three-node counterexample on the spot.

for a middle

Explain that the two structures optimize different objectives — one sum versus one distance per node — and name which problem each belongs to when the interviewer describes a scenario.

for a senior

Show you catch the confusion in a design review: someone proposes an MST for a latency-routing feature, and you redirect them to a shortest-path formulation before the ticket is written.

for a principal

Own the modeling decision: state what the business is actually paying for — total build-out spend, per-route latency, or worst-link resilience — because each of those maps to a different tree and a different algorithm.

## The two questions people confuse A **spanning tree** of a connected, undirected graph with `V` nodes is any subset of edges that connects all `V` nodes with no cycle. Every spanning tree has exactly `V-1` edges — that count is forced by the structure, not by the weights. A **minimum spanning tree (MST)** is the spanning tree whose edge weights add up to the smallest possible total. A **shortest-path tree** is a different object. Fix one source node; for every other node, take a cheapest path from the source to it. The union of those paths forms a tree rooted at the source. It minimizes `V-1` separate quantities (one distance per node), not a single sum. Both are trees on the same graph, both have `V-1` edges, and both come out of greedy algorithms — which is exactly why candidates blur them. ## The counterexample to keep in your pocket Three branch offices, with the cost of digging a fiber trench on each link: | Link | Trench cost | |---|---| | A-B | 3 | | A-C | 2 | | B-C | 2 | A spanning tree here needs two of the three links. The options cost 3+2 = 5, 3+2 = 5, or 2+2 = 4. The MST is `{A-C, B-C}` at total 4, and it **omits A-B**. Now ask the pair question: how expensive is the A-to-B route inside that tree? It is A→C→B = 4. But the graph itself offers A-B directly for 3. The MST is optimal for total cabling spend and simultaneously 33% worse than available for that one route. Nothing is broken — the MST never claimed otherwise. Notice the direction of the claim. "Minimum" in MST attaches to a **sum over the whole tree**. It does not distribute down to individual pairs, any more than the cheapest total grocery bill guarantees the cheapest price on any one item. ## What the MST path *does* guarantee There is a real per-pair property, and it is a good thing to know: the path between two nodes in an MST is a **minimum bottleneck path**. Among all paths between those nodes in the graph, it minimizes the *heaviest single edge* used, even though it may not minimize the total. In the triangle above, the A→C→B route uses a maximum edge of 2, while the direct A-B link is a single edge of 3 — so the tree route really is the better one under the bottleneck lens. That is the sense in which an MST is "good for connectivity": it keeps the worst link on every route as light as possible, not the sum on every route as small as possible. This is why MSTs show up in network design, clustering (cut the heaviest MST edges and the components fall out), and approximation schemes for tour problems — all of which care about the whole structure or the worst link, not about one pair's total. ## When they do coincide On a graph where every edge has the same weight, every spanning tree is minimum, and a breadth-first tree from the source is both an MST and a shortest-path tree. On a star-shaped graph where the source touches everything, the same set of edges is again both. Coincidence in special cases is not a general rule, and interviewers probe exactly this: "so if I need the cheapest route from headquarters to each office, do I build an MST?" The answer is no — that is a shortest-path problem from a single source, and it wants a different algorithm. ## Two more directional details - **Negative weights are fine for an MST.** The definition only involves summing a chosen edge set, and the greedy correctness argument compares crossing edges by weight; nothing assumes positivity. Several shortest-path methods, by contrast, break outright on negative edges. So "negative weights, therefore hard" is not a reflex you should apply here. - **The MST is not unique in general.** If all edge weights are distinct, the MST is unique. With ties — a very common case when weights are round numbers like trench costs in whole currency units — several different edge sets can share the same minimum total, and different algorithms, or the same algorithm with a different tie-break, may return different ones. Any of them is correct. If a downstream system needs a stable answer across runs, the fix is a deterministic tie-break rule, not a claim that the MST was unique all along.

  • So what does the path between two nodes inside an MST actually optimize?
    It is a minimum bottleneck path: among all paths between those two nodes, it minimizes the weight of the heaviest edge used, though not the total weight. In the 3-2-2 triangle, the two-hop tree route has a maximum edge of 2 while the direct link is 3, so the tree route wins on the bottleneck measure and loses on the sum.
  • Do negative edge weights break minimum spanning tree construction?
    No. An MST only sums a chosen edge set, and the greedy safety argument compares the weights of edges crossing a partition; neither step assumes weights are positive. Shifting every weight by a constant also leaves the MST unchanged, since every spanning tree has the same edge count. Negative weights break some shortest-path methods, which is where that reflex comes from.
  • Can a graph have more than one minimum spanning tree?
    Yes, whenever edge weights tie. Distinct weights guarantee a unique MST, but with ties several edge sets can hit the same minimum total, and different algorithms or tie-break orders return different ones — all correct. If a caller needs a reproducible answer, impose a deterministic tie-break, such as ordering equal-weight edges by node identifier.

The cheapest way to wire a whole building is not the cheapest wire between any two particular rooms; a global bill and a per-pair bill are different bills.

saying these in an interview costs you the question

  • Says the MST contains the shortest path between any two nodes
  • Claims MST and single-source shortest-path tree are the same tree
  • Thinks the MST always includes the globally cheapest edge touching each node
  • Assumes negative edge weights make an MST undefined
  • Assumes the MST is always unique

context

open as a page

Why does an adjacency matrix use O(V^2) space while an adjacency list uses O(V+E)?

level: juniorimportance: must knowfreq 80%

basics

~20 s

An adjacency matrix reserves a cell for every pair of vertices, so its size depends only on V, never on the edge count. An adjacency list stores one entry per vertex plus one per actual edge, so it grows with E.

open as a page

In a warehouse robot's floor grid, what plays the role of nodes and edges in a graph?

level: juniorimportance: must knowfreq 76%

basics

~20 s

Each open cell is a node; an edge joins two cells one step apart, up, down, left or right. No edge list exists anywhere: a direction array plus a bounds-and-blocked check produces a cell's neighbors on demand.

open as a page

Why does Bellman-Ford relax every edge V-1 times rather than once?

level: juniorimportance: must knowfreq 72%

basics

~20 s

After k passes over all edges, Bellman-Ford holds the best route that uses at most k edges. When no negative cycle exists, a best route never repeats a vertex, so it spans at most V-1 edges.

open as a page

What does Dijkstra's algorithm compute on a travel-time road map, and in what order does it finalize vertices?

level: juniorimportance: must knowfreq 84%

basics

~20 s

Dijkstra computes the minimum total travel time from one source to every reachable intersection - cheapest total weight, not fewest road segments. Vertices are finalized in non-decreasing distance order, so once one is popped its distance never changes.

open as a page

What does Floyd-Warshall compute, and what are its time and space complexities?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Floyd-Warshall computes the shortest-path distance between every ordered pair of vertices in a single run, not from one source. It costs O(V^3) time through three nested loops and O(V^2) space for the distance matrix.

open as a page

What does it mean for a graph to be bipartite, and how does two-coloring test it?

level: juniorimportance: must knowfreq 58%

basics

~20 s

A graph is bipartite if its vertices split into two sides with every edge crossing between them. Two-coloring tests it: color a start vertex, force each neighbour the opposite color, and fail if an edge ever joins same-colored vertices.

open as a page

What is a strongly connected component, and why does ignoring edge direction give the wrong answer?

level: juniorimportance: must knowfreq 50%

basics

~20 s

A strongly connected component is a maximal set of vertices in which every vertex can reach every other by following edge directions. Ignoring direction only proves the vertices hang together somehow; a one-way edge destroys mutual reachability without disconnecting anything.

open as a page

Why does a valid recalculation order exist for a spreadsheet only when its cell-reference graph is acyclic?

level: juniorimportance: must knowfreq 78%

basics

~20 s

A recalculation order must place every cell after the cells it reads. Inside a cycle, each cell would have to be computed before itself, which is impossible. So such an order exists only when the reference graph is acyclic.

open as a page

Why does BFS find the minimum-hop route in an unweighted network, and when does that guarantee break?

level: juniorimportance: must knowfreq 88%

basics

~20 s

BFS expands nodes strictly in order of hop count, so the first time it reaches a node it has used the fewest possible hops. The guarantee holds only while every edge costs the same; unequal edge costs break it.

open as a page

Why does depth-first search on a graph need a visited set when tree traversal does not?

level: juniorimportance: must knowfreq 85%

basics

~20 s

Graphs can contain cycles and several paths to the same vertex, so an unguarded depth-first search revisits vertices and may recurse forever. Marking a vertex the moment it is discovered makes every vertex expand exactly once, giving O(V+E).

open as a page

Kruskal's or Prim's: which MST algorithm fits a sparse edge-weighted graph, and why?

level: middleimportance: must knowfreq 78%

basics

~20 s

On a sparse graph both cost about O(E log V), and Kruskal's is the simpler fit: sort the edges, reject the cycle-closing ones cheaply. Prim's wins on dense graphs, where its scan-based form runs in O(V^2).

open as a page

In an adjacency list, matrix and edge list, what does testing whether edge u->v exists cost?

level: middleimportance: must knowfreq 62%

basics

~10 s

A matrix answers in O(1) by direct indexing. An adjacency list costs O(deg(u)) because you scan u's neighbor sequence. An unindexed edge list costs O(E), since every record may have to be checked.

open as a page

Why does searching an implicit state graph need a visited set, and what should its key be?

level: middleimportance: must knowfreq 68%

basics

~20 s

Moves are reversible, so an implicit state graph has cycles and paths reconverge; with no visited set the search re-expands states forever. The key must be a canonical encoding of the whole state, never the path used to reach it.

open as a page

Why does an edge that still relaxes on Bellman-Ford's V-th pass prove a negative cycle?

level: middleimportance: must knowfreq 64%

basics

~20 s

A further improvement means some cheaper walk uses V or more edges. A walk that long must repeat a vertex, and the loop it encloses can only reduce the total if its own weight is negative.

open as a page

Where do the log factors in Dijkstra's O((V + E) log V) binary-heap bound come from?

level: middleimportance: must knowfreq 72%

basics

~20 s

Each vertex is extracted from the min-heap once at O(log V), giving V log V. Each edge triggers at most one priority update, also O(log V), giving E log V. The two terms sum to O((V + E) log V).

open as a page

Does Floyd-Warshall produce correct distances when some edge weights are negative?

level: middleimportance: must knowfreq 62%

basics

~20 s

Yes, provided no cycle has negative total weight. The recurrence never finalises a vertex early, so a cheap route found late still improves an entry. With a negative cycle no shortest path exists and the output is meaningless.

open as a page

Why does Kahn's topological sort return a short list rather than fail when the graph has a cycle?

level: middleimportance: must knowfreq 80%

basics

~20 s

Nothing in the loop looks for cycles. Nodes on a cycle never reach in-degree zero, so they are never enqueued; the queue empties early and returns a short, valid-looking list. Compare its length to the node count.

open as a page

In BFS, why must a node be marked visited when it is enqueued rather than when it is dequeued?

level: middleimportance: must knowfreq 60%

basics

~20 s

Mark on enqueue. If nodes are only marked when removed, the same node can be pushed once per incoming edge, so the frontier swells toward the edge count and nodes get expanded repeatedly. Answers stay right; cost does not.

open as a page

In DFS over a directed module-import graph, why is a plain visited set not enough to detect a cycle?

level: middleimportance: must knowfreq 70%

basics

~20 s

A visited mark only says a vertex was seen before; a cycle needs to know it is still on the current search path. Three colours separate unseen, in-progress and finished, and only an edge into an in-progress vertex proves a cycle.

open as a page

In an undirected graph, what does a union-find union that reports already connected tell you?

level: middleimportance: must knowfreq 65%

basics

~20 s

That the edge's two endpoints already sat in one component, so the edge closes a cycle — a second path between them already exists. Union-find therefore detects cycles in an undirected graph in a single streaming pass over the edges.

open as a page

Why does union-find union by size or rank instead of always attaching the first root to the second?

level: middleimportance: must knowfreq 70%

basics

~20 s

Attaching blindly can build one long chain: a million sequential merges produce a path a million links deep, so every lookup walks O(n). Hanging the smaller tree under the larger caps height at O(log n).

open as a page

Which Dijkstra invariant breaks when one link in a latency graph has a negative weight?

level: seniorimportance: must knowfreq 76%

basics

~20 s

The finality invariant breaks: Dijkstra assumes an extracted vertex's distance can never improve, which holds only because remaining edges add non-negative amounts. One negative edge lets a cheaper route appear after a vertex is settled, and the wrong value propagates.

open as a page

In union-find, why does find follow parent links to a root instead of reading one entry?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A parent entry stores only the element x was attached to, not its group. Each set is a tree, so the group's identity is the root reached by following parent links until an element points at itself.

open as a page

In MST construction, why is the cheapest edge crossing any vertex partition safe to take?

level: middleimportance: should knowfreq 45%

basics

~20 s

Every spanning tree must cross that partition somewhere, and swapping a heavier crossing edge for the cheapest one leaves a lighter tree. So the cheapest crossing edge belongs to some minimum spanning tree, and taking it never rules out optimality.

open as a page

Do you have to build a sliding-tile puzzle's state graph before you can search it?

level: middleimportance: should knowfreq 55%

basics

~20 s

No. The graph is defined by a move rule, not by stored data: a node is a whole board arrangement, an edge is one legal tile slide. A search generates moves on demand and touches only the arrangements it actually reaches.

open as a page

In A* on a road map, what must the heuristic guarantee for the returned route to stay optimal?

level: middleimportance: should knowfreq 52%

basics

~20 s

The heuristic must be admissible: it may never overestimate the true remaining cost to the goal. A* orders its frontier by cost-so-far plus heuristic, and admissibility is what stops it finalizing the goal before a cheaper route surfaces.

open as a page

In Floyd-Warshall's triple loop, why must the intermediate-vertex loop k be outermost?

level: middleimportance: should knowfreq 55%

basics

~20 s

The k loop is outermost because each pass must finish adding waypoint k for every pair before k+1 begins. That preserves the invariant that D[i][j] holds the best cost using waypoints up to k; reordering leaves distances too large.

open as a page

Does a triangle-free graph have to be bipartite, and what is the exact test?

level: middleimportance: should knowfreq 46%

basics

~20 s

No. Triangle-free is necessary but not sufficient: a ring of five vertices holds no triangle yet cannot be two-colored. The exact characterization is that a graph is bipartite if and only if it contains no cycle of odd length.

open as a page

Why does a two-coloring check seeded only at one start vertex wrongly report bipartite?

level: middleimportance: should knowfreq 40%

basics

~20 s

Because bipartiteness is a whole-graph property checked per component. A sweep seeded at one vertex reaches only that component, so an odd cycle in an unvisited component is never examined. Restart the coloring from every still-uncolored vertex.

open as a page

showing 1–30 of 52