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 2 of 2

Why is a directed graph's condensation into strongly connected components always a DAG?

level: middleimportance: should knowfreq 40%

basics

~20 s

Contracting each strongly connected component to one node can never leave a cycle. A cycle through two component-nodes would make all their vertices mutually reachable, so those components would have been a single larger component — which maximality already forbids.

open as a page

In Kosaraju's algorithm, why does the second pass use the reversed graph in decreasing finish order?

level: middleimportance: should knowfreq 48%

basics

~20 s

The vertex finishing last in the first pass lies in a source component nothing else reaches. Reversing every edge turns that source into a sink, so a traversal started there is trapped inside one component and cannot leak outward.

open as a page

In DFS-based topological sort, why is the answer the reverse of the finishing order, not the visit order?

level: middleimportance: should knowfreq 58%

basics

~20 s

A node finishes only after every node it points to has finished, so the finishing sequence lists dependents first. Reversing it puts each node ahead of everything it points to; visit order gives no such guarantee.

open as a page

In BFS, how do you track which layer you are on, and how does that differ from recovering a route?

level: middleimportance: should knowfreq 55%

basics

~20 s

Snapshot the queue size at the top of each pass and drain exactly that many nodes: that block is one layer, which answers how many hops. Recovering the route needs a stored discoverer per node, walked backwards from the target.

open as a page

Why does DFS postorder, not preorder, give the correct order for releasing nested resources?

level: middleimportance: should knowfreq 45%

basics

~20 s

In depth-first search a vertex finishes only after everything below it has finished, so postorder emits the innermost items first — exactly what release requires. Preorder emits a container before its contents, which is acquisition order, not teardown order.

open as a page

Kruskal's on a disconnected site graph: what comes back, and what should the planner do?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Kruskal's silently returns a minimum spanning forest: one optimal tree per component, with V minus c edges instead of V minus one. The planner must compare the accepted-edge count against V minus one and report the unreachable sites.

open as a page

Neighbor iteration is implemented by scanning all E edge records once per vertex — what does that cost?

level: seniorimportance: should knowfreq 44%

basics

~10 s

The total cost is O(V*E), because each of the V vertices triggers a full pass over the edge records. Bucketing the edges by source once, in O(V+E), turns the whole sweep into O(V+E).

open as a page

Why precompute all pairs with Floyd-Warshall for 400 pick stations instead of 400 single-source runs?

level: seniorimportance: should knowfreq 48%

basics

~20 s

At 400 stations the travel-time graph is dense, so 400 queue-driven searches cost more than one triple loop of roughly 64 million add-and-compare steps. The loop yields the same matrix and makes every later query an O(1) lookup.

open as a page

When is a worker-to-shift graph bipartite by construction, and when must you actually test it?

level: seniorimportance: should knowfreq 37%

basics

~20 s

When the two sides are distinct entity types — workers and shifts — every edge crosses and bipartiteness holds by construction. When edges relate peers, worker against worker, it is a property you must test, and it can fail.

open as a page

How do you make a monorepo's topological build order deterministic across machines, and what does it cost?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A dependency graph admits many valid orders, so pin the choice: hold the ready set in a min-heap keyed on a canonical module identifier, and sort adjacency lists. Cost is a log factor on node pushes and pops.

open as a page

Why is one multi-source BFS better than k separate runs from k warehouse loading docks?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Seed all k docks into the frontier at distance zero and run once: every floor cell's first discovery is its distance to the nearest dock. That is one O(V + E) pass instead of k passes plus a per-cell minimum fold.

open as a page

A recursive DFS labeling pixel regions crashes on a large scan — how do you diagnose and fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Recursion depth in depth-first search grows with the size of the connected region being walked, not with the picture's dimensions, so one large region nests more frames than the call stack allows. Rewrite the traversal around an explicit stack.

open as a page

What does union-find's near-constant alpha(n) bound actually promise about a single find call?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Nothing about any single call. The bound is amortized over a whole sequence: m operations cost O(m alpha(n)) in total, while one individual lookup can still walk O(log n) links. Amortized here means worst-case sequence, not average input.

open as a page

When do you accept Bellman-Ford's O(V*E) instead of removing negative rebate edges to use Dijkstra?

level: principalimportance: should knowfreq 34%

basics

~10 s

Accept it when the negative edges are part of the real cost model and the queries are few or offline. Deleting or flattening them makes the algorithm faster by answering a different question.

open as a page

Why can an adjacency matrix beat a list on 300 sensors where nearly every pair is linked?

level: seniorimportance: nice to knowfreq 34%

basics

~20 s

At that density both layouts are O(V^2), so constants decide. The matrix is 90,000 contiguous cells — a few kilobytes packed as bits — with no per-edge record overhead, direct O(1) pair tests and rows that stream through cache.

open as a page

Why does Bellman-Ford need -log of each exchange rate to spot arbitrage?

level: seniorimportance: nice to knowfreq 38%

basics

~20 s

Rates compound by multiplying while route costs add, and profit means a product above one. Taking the logarithm turns the product into a sum, and negating turns "above one" into "below zero" — exactly a negative cycle.

open as a page

In lazy-deletion Dijkstra, what breaks if a vertex popped a second time is never skipped?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Nothing breaks in the output: with non-negative weights the strict-improvement test rejects every update a stale pop could attempt. The damage is performance - each stale pop re-scans a settled vertex's whole adjacency list, and heap entries grow toward one per relaxation.

open as a page

How would you check strong connectivity of a ten-million-page crawl link graph in linear time?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Pick any page as root. Traverse forward from it, then traverse from it with every link reversed. If both sweeps reach all ten million pages, the graph is strongly connected. Two linear passes, no decomposition needed.

open as a page

At a billion implicit states, what breaks first in a state-space search, and what would you trade away?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

The visited set breaks first. Generating neighbors stays cheap per state, but remembering a billion of them costs gigabytes even at eight bytes each, so the real decision is what you give up: memory, recomputation, exactness or scope.

open as a page

Floyd-Warshall builds your travel-time matrix nightly, but aisles close mid-shift — recompute or patch?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Decide by direction of change. A cheaper edge patches in O(V^2); a closed aisle makes routes more expensive, has no cheap patch, and forces a rerun. Serve stale distances only where the error is bounded and visible.

open as a page

The build DAG's critical path, not its topological order, bounds wall-clock time — how do you act on that?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

A topological order is one serialisation, not a schedule. The floor on wall-clock time is the longest weighted path through the graph, and with W workers also total work divided by W. Act on whichever floor binds.

open as a page

Union-find cannot split a merged set — how would you support un-merging identity records in a live service?

level: principalimportance: nice to knowfreq 25%

basics

~20 s

Union-find has no efficient split, so you design around it: keep merges undoable in reverse order with an undo log and no path flattening, or rebuild the affected component from stored evidence. Pick by retraction rate and component size.

open as a page

showing 31–52 of 52