Coding Interview Patterns Module 23
Weighted graphs: shortest paths and spanning trees interview questions
Interview questions on “Weighted graphs: shortest paths and spanning trees”: warm-ups, then what each harder question tests and how a good answer starts.
Warm-up questions
Short questions with short answers, each answered in full.
-
Fresher to mid
Why does Dijkstra's algorithm skip an entry whose cost is larger than the node's recorded cost, and how many entries can the heap hold?
-
Fresher
When is breadth-first search enough for a shortest path, and when do you need Dijkstra's algorithm?
-
Fresher
Why does the cheapest network that connects n points always have exactly n − 1 links and no cycle?
Start from n separate points: each link merges at most two groups into one, so connecting everything takes at least n − 1 links. A cheapest network never needs more. If it contained a cycle, removing any one link of that cycle would keep every point connected, because the rest of the cycle still joins the two ends of the removed link, and the network would cost no more. Removing links from cycles until none is left gives a connected network without cycles, which is a tree, and every tree on n points has exactly n − 1 links. With every length above zero, a cheapest network is therefore always a tree; with links of length 0 a network with a cycle can tie, but a tree of the same cost always exists.
From the lesson Min cost to connect all points: Kruskal and Prim
-
Fresher to mid
Why is a road in an undirected network critical exactly when it lies on no cycle?
If the road from a to b lies on a cycle, the rest of the cycle is a second route from a to b. Closing the road then splits nothing: any trip that used it can take that route instead, so every pair of towns that could meet still can. If the road lies on no cycle, there is no other route from a to b, because such a route plus the road would be a cycle. Closing it therefore leaves a and b unable to reach each other, which splits their group. A doubled road, a road and its bypass between the same two towns, is a cycle of two roads, so neither copy is critical. In a tree every road is critical, and in a ring none is.
From the lesson Critical connections: bridges and cut vertices
-
Fresher to mid
In a bottleneck path, a route is only as good as its worst edge. How does the relaxation step of Dijkstra's algorithm change, and why does the search stay correct?
Answered in the lesson Dijkstra variants: minimax and probabilities
-
Fresher to mid
Why does the graph of strongly connected components, the condensation, never contain a cycle?
Suppose the condensation had a cycle through components X and Y. Then some node of X reaches some node of Y, and some node of Y reaches back into X. Inside a component every node reaches every other, so every node of X would reach every node of Y and the other way round. Then X and Y together would be a group of mutual reachability larger than X, which contradicts X being a largest such group. So the condensation is a directed acyclic graph: it has a topological order, at least one source with no edge coming in and at least one sink with no edge going out, and dynamic programming over it works the way it does on any DAG.
From the lesson Strongly connected components: Kosaraju and Tarjan
-
Fresher to mid
In 0-1 BFS, why does a node reached by a zero-cost move go to the front of the deque, and one reached by a costly move go to the back?
Because that keeps the deque sorted by distance. When an entry of distance d leaves the front, everything still waiting has distance d or d + 1. A zero-cost move gives its neighbour distance d, the smallest possible, so it belongs in front of everything; a costly move gives d + 1, the largest possible, so it belongs behind everything. With those two rules the distances never decrease from front to back and never differ by more than 1, so entries leave the deque in the same order as they would leave a min-heap, and the argument that makes Dijkstra's algorithm correct applies. Each push and pop costs O(1) instead of O(log n), so the whole search runs in O(V + E). Pushing every move to the back, as plain BFS does, lets an entry of d + 1 come out before one of d.
From the lesson 0-1 BFS with a deque
-
Fresher to mid
Why is the Manhattan distance an admissible estimate on a grid with four moves where every step costs at least 1, and when does it stop being one?
With moves up, down, left and right, each step changes the row or the column by exactly 1, so any route from a cell to the goal needs at least as many steps as the Manhattan distance, |dr| + |dc|. Every step costs at least 1, so the route costs at least that much: the estimate never exceeds the true remaining cost, which is what admissible means. It stops being admissible as soon as a step can cover more than one unit of Manhattan distance for less than its length: diagonal moves, where one step covers 2 units, teleport pads, or steps that cost less than 1, such as a conveyor belt. Then the estimate must be rebuilt from the moves that exist, so that it still never exceeds the cheapest way to cover the remaining distance.
From the lesson A* search with admissible heuristics
Questions with model answers
What each question tests, the first step of a good answer and the follow-ups to expect.
-
Mid to senior
Your heap-based Dijkstra passes every test, but on a complete network of 3,000 cities, with a road between every pair, it is several times slower than a colleague's version that uses no heap at all. Explain why with numbers, and say when each version wins.
- What it tests
- Costing heap operations against array scans, remembering that E can approach V², and choosing the implementation from the graph's density instead of from the shorter-looking formula.
- First step
- Count both. The network has 3,000 × 2,999, about 9 million, one-way roads. The array version does 3,000 scans of 3,000 cities, 9 million steps, plus one check per road, and never touches a heap. The heap version makes the same road checks, plus a push and a later pop for every check that lowers a cost: find out how many do.
- Follow-ups
-
- How would you choose between the two versions automatically from n and m?
- What would a Fibonacci heap change?
- The input becomes a 3,000 × 3,000 grid of cities with four roads each. Which version now?
From the lesson Dijkstra's algorithm with a heap
Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.Opening the model answers with your pass…
Model answers open with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so the model answers can’t be opened at the moment. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to staff
A delivery app models refunds as negative tolls. A teammate's Dijkstra with lazy deletion returned the right costs on every test network, so they want to ship it. What do you tell them, and what would you use instead?
- What it tests
- Knowing which step of the correctness argument needs non-negative costs, separating a right answer from a bounded running time, and knowing the tools for negative costs.
- First step
- Find the step that needs non-negative costs: the part of a route after its first unsettled node never lowers the total. With a refund it can, so a node can leave the heap before its cheapest route is known. Then ask what the lazy version does when that node gets cheaper later: it pushes it again and expands it again.
- Follow-ups
-
- What happens if some refunds form a cycle whose total is negative?
- Could you add a constant to every toll so that none is negative?
- How would you answer many cost queries on the same network with refunds?
From the lesson Dijkstra's algorithm with a heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to mid
A teammate's Prim's algorithm returns 3 for offices at (0, 0), (1, 0) and (2, 0), where the cheapest network costs 2. The code looks like their Dijkstra. Find the bug, explain why it builds a different tree, and say how you would test for it.
- What it tests
- Knowing exactly what Prim's algorithm keeps for each office, telling it apart from a shortest-path search, and testing a greedy method against a brute force on small inputs.
- First step
- Look at what best[v] holds after each update, and compare it with what Prim's algorithm needs it to hold. Then work through the three offices by hand and write down each update.
- Follow-ups
-
- Is a shortest-path tree ever also a minimum spanning tree?
- Which small inputs would you put in a test?
- Why can the bug never show up with only two offices?
From the lesson Min cost to connect all points: Kruskal and Prim
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
You have built the cheapest cable network for 2,000 offices. A new link between offices u and v becomes available at cost c. How do you update the network without rebuilding it, and how long does an update take?
- What it tests
- Reasoning about cycles in a minimum spanning tree, updating the tree locally, and costing an update against a full rebuild.
- First step
- Adding the new link to the tree closes exactly one cycle: the tree's route from u to v, plus the new link. Ask which link of that cycle a cheapest network can do without.
- Follow-ups
-
- A link that is in the tree becomes more expensive instead.
- A link that is in the tree is cut and cannot be used at all.
- Thousands of such updates arrive every second.
From the lesson Min cost to connect all points: Kruskal and Prim
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
A grocery service wants to split 10,000 delivery addresses into exactly 8 zones so that the two closest addresses in different zones are as far apart as possible. How do you compute the zones, and why is your answer the best possible?
- What it tests
- Turning a clustering goal into a graph problem, proving that the grouping is the best possible, and estimating the work at 10,000 points.
- First step
- Restate the goal: the smallest distance between two zones must be as large as possible. Then ask which method you know already looks at distances from the smallest up and merges groups as it goes.
- Follow-ups
-
- Prove that no other split into 8 zones has a larger spacing.
- Does the same method give zones of similar size?
- New addresses arrive one at a time during the day.
From the lesson Min cost to connect all points: Kruskal and Prim
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
Your bridge finder passes the samples, but a hidden test fails: two towns joined by a road and its bypass are reported as a critical road. What is the bug, and what is the smallest test that catches it?
- What it tests
- Reading the low-link search closely, seeing why two roads between the same towns form a cycle, and building the smallest test that exposes a bug.
- First step
- Look at how the search skips the road it arrived by, and run it by hand on two towns joined by two roads. Which of the two roads should the search skip at the second town?
- Follow-ups
-
- Does the same bug change the critical towns?
- What would roads from a town to itself do?
- How would you store the roads so that the check is one comparison?
From the lesson Critical connections: bridges and cut vertices
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
A broadband network has 200,000 street cabinets and 350,000 fibre links, with the exchange at cabinet 0. For every link whose cut would disconnect cabinets, report how many cabinets would lose their path to the exchange. Do it in one pass over the network.
- What it tests
- Extending the low-link search with extra counts, knowing which side of a critical link holds the exchange, and keeping the work linear.
- First step
- Start the low-link search at the exchange. When the link from u to its child v is critical, ask which cabinets lie on the far side of it, and what the search could count as towns finish.
- Follow-ups
-
- Some cabinets are in another piece of the network, with no path to the exchange at all.
- Which single cabinet failure cuts off the most cabinets?
- The network is far too deep for a recursive search.
From the lesson Critical connections: bridges and cut vertices
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Senior to staff
A connected road network has 40 critical roads. With one new road, which road leaves the fewest critical roads? And how many new roads are needed so that no road is critical at all?
- What it tests
- Shrinking a network to the structure of its critical roads, reasoning about which roads one new road protects, and bounding the number of new roads.
- First step
- Shrink every group of towns joined without critical roads into one node, and look at what the 40 critical roads become. Then ask which critical roads a single new road puts on a cycle.
- Follow-ups
-
- Why can that lower bound always be met?
- The network is in several pieces.
- New roads may only join towns at most 10 km apart.
From the lesson Critical connections: bridges and cut vertices
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to staff
A hiking app must find the least strenuous route on height maps of 2,000 × 2,000 cells, with heights from 0 to 10,000 metres. Would you use Dijkstra's algorithm with max, binary search on the effort with breadth-first search, or union-find over sorted steps? Estimate the work of each.
- What it tests
- Estimating three standard methods on a large grid with numbers, and choosing by their time, their memory and what else each one can answer.
- First step
- Size the graph first: 4 million cells and about 8 million steps between neighbours. Then cost each method: one Dijkstra run with an entry per successful relaxation, about 14 breadth-first searches for a height range of 10,000, or one sort of 8 million steps followed by nearly constant union-find work per step.
- Follow-ups
-
- The app must answer 100,000 queries a day for different start and end cells on the same map.
- The service is written in Python and has 256 MB of memory.
- Most of the terrain is flat, so many steps are equal.
From the lesson Dijkstra variants: minimax and probabilities
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A cycling app rates a route by its highest point minus its lowest point and wants the route between two corners of a height map with the smallest rating. A colleague adapts Dijkstra's algorithm with one label per cell. Does that work? If not, what does?
- What it tests
- Checking a custom route cost against both properties Dijkstra's algorithm needs, building a counterexample, and designing a correct method from a fixed parameter and a bottleneck search.
- First step
- Test the cost against both properties. A longer route never has a smaller range, so the first one holds. For the second, look for two routes into the same cell whose order flips after one more step: one that dips low and one that stays high.
- Follow-ups
-
- Give the smallest counterexample you can.
- How fast is your method on a 300 × 300 map with heights from 0 to 100?
- What if the rating is only the highest point of the route?
From the lesson Dijkstra variants: minimax and probabilities
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A network tool multiplies link reliabilities to rank routes through a mesh of thousands of relays. On long routes every route scores exactly 5e-324, and the tool picks a worse route. Explain what happened, with numbers, and fix it.
- What it tests
- Floating-point underflow in long products, why ties then break the ranking, and the logarithm transform that keeps Dijkstra's algorithm usable.
- First step
- Work out when a product of reliabilities leaves the range of doubles. The smallest normal double is about 2.2 × 10⁻³⁰⁸, so a product of links of 0.7 falls below it after 1,987 links and then sticks at the smallest positive double, 5 × 10⁻³²⁴.
- Follow-ups
-
- Would exact fractions or decimals fix it?
- Some links have a reliability of exactly 1, and some of exactly 0. Anything special?
- How would you show users the reliability of a route with 2,100 links?
From the lesson Dijkstra variants: minimax and probabilities
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A platform has 3,000 services and 40,000 dependencies of the form "A calls B". Releases must deploy a service after everything it calls, but some services call each other in cycles. How do you find the groups that must ship together and an order for the groups?
- What it tests
- Recognising dependency cycles as a graph structure, turning that structure into a release order, and costing the work.
- First step
- Treat "A calls B" as an edge from A to B. Ask which services can never be deployed strictly one after another, and what is left when each such group is treated as a single service.
- Follow-ups
-
- What does one very large group tell you about the platform?
- How do you show the team one cycle as evidence for a group?
- The list of dependencies changes with every merged change.
From the lesson Strongly connected components: Kosaraju and Tarjan
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to staff
An airline's 600 airports are joined by one-way routes, and some airports cannot be reached from others. What is the fewest number of new one-way routes that lets every airport reach every other, and why can fewer not work?
- What it tests
- Shrinking a directed network, deriving a lower bound on the new routes, and knowing that the bound can always be met.
- First step
- Shrink each strongly connected group of airports to one node. Which groups need a new route coming in, which need one going out, and how many of each can a single new route serve?
- Follow-ups
-
- Why does a single group need no new route, although it is both a source and a sink?
- How would you choose the routes for 3 sources and 2 sinks?
- Which airports can already reach every other airport?
From the lesson Strongly connected components: Kosaraju and Tarjan
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
A release has 200 feature flags, each on or off, and 1,500 rules such as "if A is on, B must be off" or "A or B must be on". Before each release you must say whether some setting satisfies every rule and produce one. How, in linear time?
- What it tests
- Turning two-flag rules into a graph, deciding in linear time whether a setting exists, and building one from the graph.
- First step
- Write every rule as "x or y" over the literals "A on" and "A off", so that "if A is on, B must be off" becomes "A off or B off". Ask what such a rule forces when one of its literals is false.
- Follow-ups
-
- How do the components show that no setting exists?
- How do you pick the values once you know a setting exists?
- Some rules involve three flags.
From the lesson Strongly connected components: Kosaraju and Tarjan
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
On a 2,000 × 2,000 warehouse floor where clearing a crate costs 1 and moving costs nothing, how much work does 0-1 BFS save over Dijkstra's algorithm with a heap, and is the saving worth a second implementation? Estimate with numbers.
- What it tests
- Estimating the price per operation of a deque against a heap, scaling measured counts, and judging when a constant factor is worth code.
- First step
- Both methods push about one entry per cell, about 4 million here, so the difference lies in the price of each entry: O(1) for a deque, and about log₂ of the number of waiting entries for a heap. Estimate how many entries wait at once.
- Follow-ups
-
- The costs become 0, 1 or 2. What then?
- Memory is tight. Which of the two needs less?
- Would you write 0-1 BFS in an interview if Dijkstra's algorithm already passes?
From the lesson 0-1 BFS with a deque
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A teammate's 0-1 BFS for a conveyor-tile grid marks each tile as done the first time it is pushed, like a plain BFS. The same code passed every test of an earlier crate-clearing problem, but fails here. Explain why, give a failing grid and fix it.
- What it tests
- Recognising whether costs sit on cells or on moves, building a small counterexample, and knowing which checks 0-1 BFS needs.
- First step
- Ask where the cost sits. On a crate floor every way into a cell costs the same, so the first offer is the best one. On a conveyor floor the cost depends on the tile being left, so a neighbour that comes out later can offer a cheaper way in. Try the smallest grids where that can happen.
- Follow-ups
-
- Is the stale check still needed once a tile is pushed on every improvement?
- Can a tile enter the deque more than twice?
- Does the same marking break Dijkstra's algorithm on these grids?
From the lesson 0-1 BFS with a deque
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to staff
A city has 100,000 junctions and 300,000 one-way streets. Turning a street round needs one permit. How do you find the fewest permits needed to drive from junction A to junction B, and how long does it take?
- What it tests
- Modelling reversals as a costly second copy of every edge, choosing 0-1 BFS, and arguing about its size and its correctness.
- First step
- Build a graph in which every street u → v gives two edges: u → v at cost 0, driven as it is, and v → u at cost 1, driven after a reversal. The fewest permits is then a shortest path whose costs are only 0 and 1.
- Follow-ups
-
- Why does a cheapest route never need a street reversed and then driven the original way?
- How much memory does the doubled graph take?
- Some streets may not be reversed at all, and highways need 3 permits. What changes?
From the lesson 0-1 BFS with a deque
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A game moves units on a 512 × 512 tile map in eight directions, and a diagonal step costs 1.4. A teammate's A* with the Manhattan estimate sometimes returns longer paths than a slow Dijkstra. Explain why, fix it, and say what the fix costs in speed.
- What it tests
- Checking an estimate against the move set, choosing an estimate for eight directions, and weighing a tight estimate against a correct one.
- First step
- Check the estimate against a single move: compare what one diagonal step costs with how much it lowers the Manhattan distance. What does that mean for cells close to the goal?
- Follow-ups
-
- Why not use the straight-line Euclidean distance instead?
- Diagonal steps may not cut the corner of a wall. Does the estimate change?
- Costs are now floating-point numbers. What can go wrong with ties?
From the lesson A* search with admissible heuristics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
-
Mid to senior
Your A* with the Manhattan estimate gives right answers, but on large open maps it settles almost every cell, as Dijkstra does. Why, and what small change fixes it? Show that the change keeps every answer right.
- What it tests
- Seeing why equal priorities slow A* down, choosing a tie rule, and separating speed from correctness.
- First step
- Look at the priorities f = g + h of the cells on an open map and count how many of them are equal. Then ask what decides the order of equal keys in your heap.
- Follow-ups
-
- Is preferring the entry with more time spent always better?
- What does the change do in a narrow maze?
- How do you test that the change keeps every answer right?
From the lesson A* search with admissible heuristics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
A delivery app answers 1,000 route queries a second on a fixed road network of 2 million junctions with travel times as costs. The straight-line estimate is weak because roads wind. How would you make A* fast, and what would you precompute?
- What it tests
- Precomputing lower bounds that stay consistent, estimating their memory, and choosing where to place them.
- First step
- Measure how many junctions A* settles with the straight-line estimate, divided by the top speed to stay admissible. Then ask what you could compute once, while the network stays the same, that bounds the remaining time more tightly.
- Follow-ups
-
- How much memory do 16 landmarks need?
- Where should the landmarks go?
- Streets are one-way. Which direction do you precompute?
From the lesson A* search with admissible heuristics
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 2 minutes
All Coding Interview Patterns interview questions · The Coding Interview Patterns track