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 pageshowhide
explore
- Representations & Modeling8 questions
- Adjacency List, Matrix & Edge List4 questions
- Implicit Graphs & Grid Modeling4 questions
- BFS & DFS Traversal8 questions
- Breadth-First Search4 questions
- Depth-First Search4 questions
- Union-Find (DSU)5 questions
- DAGs & Topological Sort5 questions
- Shortest Paths14 questions
- Dijkstra & A*5 questions
- Bellman-Ford4 questions
- Floyd-Warshall5 questions
- Minimum Spanning Trees4 questions
- Special Graph Classes8 questions
- Bipartite Graphs & Two-Coloring4 questions
- Strongly Connected Components4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2Why is a directed graph's condensation into strongly connected components always a DAG?
basics
~20 sContracting 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.
In Kosaraju's algorithm, why does the second pass use the reversed graph in decreasing finish order?
basics
~20 sThe 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.
In DFS-based topological sort, why is the answer the reverse of the finishing order, not the visit order?
basics
~20 sA 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.
In BFS, how do you track which layer you are on, and how does that differ from recovering a route?
basics
~20 sSnapshot 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.
Why does DFS postorder, not preorder, give the correct order for releasing nested resources?
basics
~20 sIn 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.
Kruskal's on a disconnected site graph: what comes back, and what should the planner do?
basics
~20 sKruskal'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.
Neighbor iteration is implemented by scanning all E edge records once per vertex — what does that cost?
basics
~10 sThe 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).
Why precompute all pairs with Floyd-Warshall for 400 pick stations instead of 400 single-source runs?
basics
~20 sAt 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.
When is a worker-to-shift graph bipartite by construction, and when must you actually test it?
basics
~20 sWhen 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.
How do you make a monorepo's topological build order deterministic across machines, and what does it cost?
basics
~20 sA 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.
Why is one multi-source BFS better than k separate runs from k warehouse loading docks?
basics
~20 sSeed 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.
A recursive DFS labeling pixel regions crashes on a large scan — how do you diagnose and fix it?
basics
~20 sRecursion 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.
What does union-find's near-constant alpha(n) bound actually promise about a single find call?
basics
~20 sNothing 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.
When do you accept Bellman-Ford's O(V*E) instead of removing negative rebate edges to use Dijkstra?
basics
~10 sAccept 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.
Why can an adjacency matrix beat a list on 300 sensors where nearly every pair is linked?
basics
~20 sAt 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.
Why does Bellman-Ford need -log of each exchange rate to spot arbitrage?
basics
~20 sRates 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.
In lazy-deletion Dijkstra, what breaks if a vertex popped a second time is never skipped?
basics
~20 sNothing 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.
How would you check strong connectivity of a ten-million-page crawl link graph in linear time?
basics
~20 sPick 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.
At a billion implicit states, what breaks first in a state-space search, and what would you trade away?
basics
~20 sThe 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.
Floyd-Warshall builds your travel-time matrix nightly, but aisles close mid-shift — recompute or patch?
basics
~20 sDecide 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.
The build DAG's critical path, not its topological order, bounds wall-clock time — how do you act on that?
basics
~20 sA 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.
Union-find cannot split a merged set — how would you support un-merging identity records in a live service?
basics
~20 sUnion-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.
showing 31–52 of 52