{"id":"cheapest-flights-within-k-stops","title":"Cheapest Flights Within K Stops","difficulty":"medium","patterns":["bellman-ford"],"primaryConcept":"graph-shortest-path-negative","concepts":["graph-shortest-path-negative"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"weighted-graph-edges","primaryParam":"flights","sizeMetric":"nodes-plus-edges","constraints":["positive","dag"],"sizes":[8,16,32,64],"valueRange":{"min":1,"max":100},"secondaryParams":{"n":{"strategy":"scale-with-primary"},"src":{"strategy":"fixed","value":0},"dst":{"strategy":"fixed","value":1},"k":{"strategy":"proportion","proportion":0.5}}},"description":"There are `n` cities labeled `0..n-1` and directed flights where `flights[i] = [from, to, price]`.\n\nReturn the cheapest price to travel from `src` to `dst` using at most `k` stops. If there is no such route, return `-1`.\n\nA route with `k` stops can use at most `k + 1` flight edges, so use bounded Bellman-Ford relaxation by number of edges.","examples":[{"input":"n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1","output":"200","explanation":"The route 0->1->2 has one stop and costs 200."},{"input":"n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0","output":"500","explanation":"With zero stops only direct flights are allowed."}],"constraints":[{"id":"1-n-100","text":"1 <= n <= 100","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":100}},{"id":"0-len-flights-n-n-1","text":"0 <= len(flights) <= n * (n - 1)"},{"id":"flights-i-from-to-price","text":"flights[i] = [from, to, price]","check":{"kind":"shape","target":"flights","shape":"tupleArray","tupleLength":3}},{"id":"0-from-to-n","text":"0 <= from, to < n","check":[{"kind":"valueRange","target":"flights","selector":"tupleItemsAtIndex","index":0,"min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"flights","selector":"tupleItemsAtIndex","index":1,"min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"from-to","text":"from != to","check":{"kind":"compare","target":"flights","left":{"field":0},"op":"!=","right":{"field":1}}},{"id":"1-price-10-4","text":"1 <= price <= 10^4","check":{"kind":"valueRange","target":"flights","selector":"tupleItemsAtIndex","index":2,"min":1,"max":10000}},{"id":"0-src-dst-n","text":"0 <= src, dst < n","check":[{"kind":"valueRange","target":"src","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"dst","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"src-dst","text":"src != dst","check":{"kind":"compare","left":{"valueOfInput":"src"},"op":"!=","right":{"valueOfInput":"dst"}}},{"id":"0-k-n","text":"0 <= k < n","check":{"kind":"valueRange","target":"k","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}}}],"starterCode":"class Solution:\n    def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n        # Your code here\n        pass","functionName":"findCheapestPrice","testCases":[{"id":"1","input":{"n":3,"flights":[[0,1,100],[1,2,100],[0,2,500]],"src":0,"dst":2,"k":1},"expected":200,"description":"One-stop route beats the direct flight."},{"id":"2","input":{"n":3,"flights":[[0,1,100],[1,2,100],[0,2,500]],"src":0,"dst":2,"k":0},"expected":500,"description":"Zero stops only permits direct flights."},{"id":"3","input":{"n":4,"flights":[[0,1,100],[1,2,100],[2,3,100],[0,3,500]],"src":0,"dst":3,"k":1},"expected":500,"description":"Cheaper three-edge route is not allowed with one stop."},{"id":"4","input":{"n":4,"flights":[[0,1,100],[1,2,100],[2,3,100],[0,3,500]],"src":0,"dst":3,"k":2},"expected":300,"description":"Two stops allow the cheaper three-edge route."},{"id":"5","input":{"n":3,"flights":[[0,1,200]],"src":0,"dst":2,"k":2},"expected":-1,"description":"Destination is unreachable."},{"id":"6","input":{"n":5,"flights":[[0,1,5],[1,4,5],[0,2,2],[2,3,2],[3,4,2]],"src":0,"dst":4,"k":1},"expected":10,"description":"A two-edge path is best when only one stop is allowed."},{"id":"7","input":{"n":5,"flights":[[0,1,5],[1,4,5],[0,2,2],[2,3,2],[3,4,2]],"src":0,"dst":4,"k":2},"expected":6,"description":"One extra stop unlocks a cheaper path."},{"id":"8","input":{"n":4,"flights":[[0,1,10],[1,2,10],[2,1,1],[2,3,10],[0,3,100]],"src":0,"dst":3,"k":3},"expected":30,"description":"A cycle does not help when the bounded edge count is enforced."},{"id":"h1","input":{"n":5,"flights":[[0,1,50],[1,4,50],[0,2,20],[2,3,20],[3,4,20],[0,4,200]],"src":0,"dst":4,"k":1},"expected":100,"description":"The cheapest valid route uses exactly the allowed one stop."},{"id":"h2","input":{"n":4,"flights":[[0,1,1],[1,2,1],[2,3,1]],"src":0,"dst":3,"k":1},"expected":-1,"description":"No route reaches the destination within the stop limit."},{"id":"h3","input":{"n":4,"flights":[[0,1,5],[1,2,5],[2,3,5],[0,3,50],[1,3,100]],"src":0,"dst":3,"k":2},"expected":15,"description":"The cheapest valid route uses exactly the maximum allowed two stops."},{"id":"h4","input":{"n":4,"flights":[[0,1,100],[1,2,100],[2,3,100],[0,3,500],[1,3,450]],"src":0,"dst":3,"k":2},"expected":300,"description":"With zero stops allowed, the direct flight is required even when an indirect path is cheaper."},{"id":"cheaper-route-needs-two-stops","input":{"n":4,"flights":[[0,1,1000],[0,2,100],[2,1,100],[1,3,100]],"src":0,"dst":3,"k":1},"expected":1100,"description":"The cheapest route, 0 -> 2 -> 1 -> 3 for 300, needs two stops, so with k = 1 the answer is 0 -> 1 -> 3 for 1100."}],"hints":[{"level":1,"content":"A route with k stops has at most k + 1 flight edges."},{"level":2,"content":"Relax every flight once for each allowed edge count."},{"level":3,"content":"Keep layers separate so one pass cannot use two flights from the same pass."}],"guidedFlow":{"version":2,"progressRevision":"cheapest-flights-within-k-stops-2026-11-20-price-table-rows","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"rolling-snapshot-relaxation","name":"Two rolling rows","summary":"Keep only the row above and the row being filled, and reuse them for every flight limit.","decisionReason":"Each row reads only the row above it, so two rows of n prices produce the same last row as the full table.","complexity":{"time":"O(k * (n + e))","space":"O(n)"},"tradeoffs":["Uses O(n) space, but the prices for smaller flight limits are overwritten as the passes go on."],"isViable":true,"isOptimal":false},{"id":"bounded-relaxation","name":"Price table by flight limit","summary":"Keep the cheapest price to every city for each flight limit from 0 to k + 1, and fill the rows in order.","decisionReason":"Row r holds the cheapest price to each city using at most r flights. It starts as a copy of row r - 1 and then lets every flight extend a trip from that row, so row k + 1 under dst is the answer.","complexity":{"time":"O(k * (n + e))","space":"O(k*n)"},"tradeoffs":["Stores (k + 2) * n prices, more than the two rows that are strictly needed."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-stop-table","title":"Create the table and set the starting cell","description":"Make a table with a row for every flight limit from 0 to `k + 1` and a column for every city. Fill it with a no-trip value larger than any real total, then set the starting city to 0 in row 0.","commonMistakes":["Making `k + 1` rows, which leaves no row for a trip that uses all `k + 1` flights","Leaving the starting city at the no-trip value in row 0, so no flight ever has a trip to extend"],"hint":"`k` stops allow `k + 1` flights, and row 0 is one more row on top of those.","semanticSpec":{"intent":"Initialize bounded Bellman-Ford price state before any flight relaxation.","doneWhen":"The solution creates a stop-layered price table sized by allowed edge count and city count, fills unreachable entries with an INF-like sentinel, and sets the source city in layer 0 to price 0 before relaxation starts.","shouldFailWhen":"This step should fail if the price state is not indexed by both stop layer and city, if the source is not seeded at layer 0, or if the table is allocated inside the relaxation loop.","roles":["price table","stop layer","city index","source city","unreachable sentinel"],"mustProve":["The price state has separate storage for each allowed edge count from 0 through k + 1.","Each stop layer contains per-city price entries.","The source city starts at price 0 in the zero-edge layer before the flight loops."],"mustNotAccept":["A scalar price value with no per-city indexed state.","A single shared city-price row reused for every stop layer.","A table allocated inside the flight relaxation loop.","A layered table where the source is never seeded to 0 before relaxation."],"equivalentVariants":["Use a 2D list, array, or equivalent indexed table for stop layers and cities.","Use an equivalent layer-indexed distance representation as long as layer 0 records only the source as reachable."],"proofSnippets":[{"id":"py-cheapest-flights-init-stop-table","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-stop-table","readMode":"graph-value-query-v1"}]}},{"id":"carry-forward","title":"Copy each row down before trying flights","description":"For each flight limit in turn, carry the prices of the current row into the next row before any flight is tried. A trip that fits in fewer flights still fits the larger limit.","commonMistakes":["Filling the next row only where a flight lands, which drops cheaper trips that use fewer flights"],"hint":"Without the copy, a city that no flight improves falls back to the no-trip value in the next row.","semanticSpec":{"intent":"Propagate indexed price state from one stop layer to the next.","doneWhen":"This step is done when each next-layer row starts from a distinct previous-layer snapshot before relaxation, so carry-forward prices are preserved without allowing in-place chaining inside the same pass.","shouldFailWhen":"This step should fail if the table is initialized but no indexed state is carried forward.","roles":["price table","current stop layer","next stop layer","city index"],"mustProve":["The next layer is distinct from the previous layer.","Known prices from the previous layer are available before flight relaxations in the next layer.","Writes for the current pass do not change the source state used by other flights in that same pass."],"mustNotAccept":["A table allocation with no carry-forward loop.","A loop that overwrites the next layer without reading the previous layer."],"equivalentVariants":["Copy a full row before relaxing flights.","Conditionally write each previous-layer price into the next layer."],"proofSnippets":[{"id":"py-cheapest-flights-carry-forward","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"carries_forward_indexed_numeric_state","scope":"carry-forward","readMode":"numeric-state-value-query-v1"}]}},{"id":"compute-candidates","title":"Work out what each flight offers","description":"For every flight, take its starting city's price in the current row and add the flight's price. A flight whose starting city has no trip yet has nothing to offer and is skipped.","commonMistakes":["Reading the starting city's price from the row being filled, which lets one pass chain several flights","Adding the flight's price to the arriving city's price instead of the starting city's"],"hint":"The starting price comes from the row that is already finished, never from the row being filled.","semanticSpec":{"intent":"Build weighted relaxation candidates from flight entries and previous-layer prices.","doneWhen":"The solution repeatedly scans flights, binds source/destination/cost roles, and compares a weighted candidate against the destination price.","shouldFailWhen":"This step should fail if flights are scanned without computing a source-price-plus-cost candidate.","roles":["flight edge","source city","destination city","flight cost","candidate price"],"mustProve":["Flight entries are destructured into source, destination, and weight roles.","A candidate price combines the prior source price with the flight cost."],"mustNotAccept":["A loop over flights that ignores the flight cost.","A candidate based on the destination price instead of the source price."],"equivalentVariants":["Store the candidate in a local variable before comparing.","Compute the candidate inline in the cheaper-price guard."],"proofSnippets":[{"id":"py-cheapest-flights-compute-candidates","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                pass"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"computes_weighted_edge_relaxation_candidate","scope":"relax-candidate","readMode":"graph-value-query-v1"}]}},{"id":"relax-flights","title":"Keep the cheaper price","description":"Compare each flight's offer with the price already under its arriving city in the next row, and write the offer when it is lower.","commonMistakes":["Writing every offer without comparing, so a costlier flight later in the list overwrites a cheaper price"],"hint":"The copied-down price and every flight into the same city compete for one cell, and the lowest stays.","semanticSpec":{"intent":"Perform bounded Bellman-Ford relaxation over all flights.","doneWhen":"The solution repeats passes over the flight list and writes improved prices into the next stop layer.","shouldFailWhen":"This step should fail if there is no repeated relation pass or no weighted metric write.","roles":["flight edge","source city","destination city","price table","candidate price"],"mustProve":["The solution loops over relation entries from flights.","A candidate price combines a previous source price with the flight cost.","The destination price state is updated when the candidate is cheaper."],"mustNotAccept":["A single direct-flight lookup without repeated passes.","A loop that scans flights but never updates distance or price state."],"equivalentVariants":["Use a 2D DP table by edge count.","Use another layer-separated representation as long as each pass reads the prior layer and writes the next layer."],"proofSnippets":[{"id":"py-cheapest-flights-relax-layers","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                dp[step + 1][v] = candidate"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"relax-all-edges","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return the price in the last row","description":"Once every row is filled, read the destination's cell in row `k + 1`. Return it, or -1 if it still holds the no-trip value.","commonMistakes":["Reading row `k`, which allows one flight fewer than the limit","Returning the no-trip value itself when the destination was never reached"],"hint":"The last row is the one that allows `k + 1` flights.","semanticSpec":{"intent":"Return the terminal result from the completed weighted relaxation state.","doneWhen":"The solution reads the final destination price after all relaxation rounds and returns that terminal result.","shouldFailWhen":"This step should fail if the relaxation result is never returned.","roles":["final layer","destination city","unreachable sentinel","terminal answer"],"mustProve":["The terminal result is returned after bounded relaxation has completed."],"mustNotAccept":["Returning a loop counter or unrelated scalar.","Returning before all allowed relaxation passes have completed."],"equivalentVariants":["Store the final destination value in a variable before returning it.","Return the final destination table entry directly after checking the sentinel."],"proofSnippets":[{"id":"py-cheapest-flights-return-result","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                dp[step + 1][v] = candidate\n    answer = dp[k + 1][dst]\n    if answer == INF:\n        return -1\n    return answer"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_relaxed_metric_result","scope":"return-result","readMode":"graph-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","title":"Find the cheapest trip within a stop limit","workspacePanel":"problem","body":["Flights are one-way, join numbered cities, and each has a price. You are given a starting city, a destination and a stop limit. A stop is a city the trip lands in before the destination.","Return the lowest total price of a trip that makes at most that many stops, or -1 if no trip fits.","On the map, each arrow is a flight, and the number beside it is its price in dollars. The trip goes from city 0 to city 3."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"map","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"stop-limit","kind":"case-probe","title":"With at most 1 stop, what is the cheapest trip from city 0 to city 3?","workspacePanel":"visualizer","options":[{"id":"one-stop","label":"$400, flying 0 → 1 → 3","rationale":"This trip stops only in city 1, and $100 + $300 = $400. The direct flight also fits the limit but costs $500. One stop allows two flights, and in general a limit of `k` stops allows `k + 1` flights.","isCorrect":true},{"id":"two-stops","label":"$300, flying 0 → 1 → 2 → 3","rationale":"$300 is the lowest total to city 3, but the trip lands in city 1 and city 2. That is two stops, one over the limit.","isCorrect":false},{"id":"direct","label":"$500, flying 0 → 3 direct","rationale":"The direct flight makes no stops, so it is allowed. One stop is allowed too, so the trips that land once on the way have to be priced as well.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"map","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"flight-budget-state","kind":"case-probe","title":"Three trips reach city 3, using 1, 2 and 3 flights. Which of their prices must be kept to answer any flight limit?","workspacePanel":"visualizer","options":[{"id":"all-three","label":"All three: $500, $400 and $300","rationale":"The limit decides which one wins. At most 1 flight gives $500, at most 2 gives $400, and at most 3 gives $300.","isCorrect":true},{"id":"cheapest-only","label":"Only $300, the cheapest of the three","rationale":"Under a limit of 2 flights the $300 trip is not allowed, and the $400 that should win was thrown away.","isCorrect":false},{"id":"shortest-only","label":"Only $500, the one with the fewest flights","rationale":"$500 fits every limit of at least one flight, but with 2 flights allowed the $400 trip is cheaper.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"map","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"price-table","kind":"info","title":"One row per flight limit, one column per city","workspacePanel":"visualizer","body":["So each city needs its cheapest price for every flight limit, and the prices go in a table. Each column is a city. Each row is a flight limit, and the row number is the number of flights allowed: row 0 allows none, row 2 allows two.","A limit of `k` stops needs rows 0 through `k + 1`. For at most 1 stop that is three rows."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-table","state":{"grid":[["?","?","?","?"],["?","?","?","?"],["?","?","?","?"]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"cell-meaning","kind":"case-probe","title":"A limit of 2 flights should be answered by reading one cell. What does row 2 under city 3 have to hold?","workspacePanel":"visualizer","options":[{"id":"at-most","label":"The cheapest price to reach city 3 using at most 2 flights","rationale":"At most 2 flights is what the limit says, so the cell covers the direct flight as well as the two-flight trip. Every cell follows the same rule: row r under a city is the cheapest price to reach that city from the starting city using at most r flights.","isCorrect":true},{"id":"exactly","label":"The cheapest price to reach city 3 using exactly 2 flights","rationale":"The direct flight uses one flight and is allowed too. If it were the cheaper trip, a cell for exactly 2 flights would miss it, and the answer would need row 1 as well.","isCorrect":false},{"id":"any-count","label":"The cheapest price to reach city 3 using any number of flights","rationale":"That is $300, a three-flight trip, which a limit of 2 flights does not allow.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"answer-cell","state":{"grid":[["?","?","?","?"],["?","?","?","?"],["?","?","?","?"]],"r":2,"c":3,"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"row-zero","kind":"case-probe","title":"Row 0 allows no flights at all. What belongs in it?","workspacePanel":"visualizer","options":[{"id":"start-only","label":"$0 under city 0, and a no-trip mark under every other city","rationale":"Without a flight the trip is still in city 0 and has paid $0. No other city can be reached, so those cells get a no-trip mark, drawn as ∞. In code it is a number larger than any total a trip could cost, so it loses every comparison against a real price.","isCorrect":true},{"id":"all-zero","label":"$0 under every city, because nothing has been paid yet","rationale":"A $0 under city 3 would say city 3 can be reached for free. With no flights, only city 0 can be reached.","isCorrect":false},{"id":"direct-prices","label":"$100 under city 1 and $500 under city 3, the direct flights","rationale":"Each of those trips uses one flight, so they belong to row 1.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-table","state":{"grid":[["?","?","?","?"],["?","?","?","?"],["?","?","?","?"]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Row 0 is filled, and every other cell starts at ∞. Next, row 1: at most one flight.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seeded","state":{"grid":[[0,"∞","∞","∞"],["∞","∞","∞","∞"],["∞","∞","∞","∞"]],"filled":[[0,0],[0,1],[0,2],[0,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}},{"id":"row-1-copied","state":{"grid":[[0,"∞","∞","∞"],[0,"∞","∞","∞"],["∞","∞","∞","∞"]],"r":1,"c":0,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3]],"changed":[[1,0]],"dependsOn":[[0,0]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}},{"id":"row-1-done","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],["∞","∞","∞","∞"]],"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3]],"changed":[[1,1],[1,3]],"dependsOn":[[0,0]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]],"current":0,"highlighted":[1,3],"activeEdges":[[0,1],[0,3]]}}}]},"beats":[{"id":"city-0-in-row-1","title":"Row 1 allows at most one flight. What is the cheapest price for city 0 in row 1?","options":[{"id":"zero","label":"$0, the same as in row 0","rationale":"Staying in city 0 uses no flights, and no flights is within a limit of one. The same goes for every city, so row 1 begins as a copy of row 0.","isCorrect":true},{"id":"infinity","label":"∞, because no flight lands in city 0","rationale":"Row 1 allows a flight but does not require one. The trip that never leaves city 0 still counts, at a price of $0.","isCorrect":false},{"id":"hundred","label":"$100, the cheapest flight out of city 0","rationale":"$100 is the price of leaving city 0 for city 1. The cell is the price of being in city 0.","isCorrect":false}]},{"id":"row-1-flights","title":"Which flights can put a price into row 1?","options":[{"id":"from-start","label":"0 → 1 and 0 → 3, the two flights that leave city 0","rationale":"A one-flight trip has to begin where a zero-flight trip ends, and row 0 has a price only under city 0. The two cells become $0 + $100 = $100 and $0 + $500 = $500.","isCorrect":true},{"id":"all-five","label":"All five flights, each writing its own price","rationale":"Flight 1 → 2 would need a trip that is already in city 1. Row 0 has ∞ there, so the flight has nothing to continue.","isCorrect":false},{"id":"cheapest-first","label":"Only 0 → 1, the cheapest flight out of city 0","rationale":"Flight 0 → 3 starts in city 0 as well. Its $500 is the only price a single flight can give city 3, so it is written too.","isCorrect":false}]}]},{"id":"trace-row-2","kind":"dry-run","source":"trace-example","title":"Row 2 starts as a copy of row 1","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"row-2-copied","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,"∞",500]],"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[[2,0],[2,1],[2,3]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}},{"id":"flight-1-2","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,500]],"r":2,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[[2,2]],"dependsOn":[[1,1]],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]],"current":1,"highlighted":[2],"activeEdges":[[1,2]]}}},{"id":"flight-1-3","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,400]],"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]],"current":1,"highlighted":[3],"activeEdges":[[1,3]]}}},{"id":"answer-cell","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,400]],"r":2,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]],"activeEdges":[[0,1],[1,3]]}}}]},"beats":[{"id":"no-chaining","title":"Flights 1 → 2 and 2 → 3 are tried in that order. What do they write in row 2?","options":[{"id":"city-2-only","label":"$200 under city 2, and nothing under city 3","rationale":"Flight 1 → 2 reads city 1 from row 1: $100 + $100 = $200. Flight 2 → 3 reads city 2 from row 1 as well, where it is still ∞, so it has nothing to offer.","isCorrect":true},{"id":"chain","label":"$200 under city 2, then $300 under city 3","rationale":"The $200 was just written into row 2. Flight 2 → 3 reads its starting price from row 1, which has ∞ under city 2. Reaching city 3 for $300 takes three flights, and row 2 allows two.","isCorrect":false},{"id":"neither","label":"Nothing, because city 2 has no price yet","rationale":"City 2 is where flight 1 → 2 arrives. Its starting city is city 1, which row 1 has at $100, so it writes $100 + $100 = $200.","isCorrect":false}]},{"id":"cheaper-wins","title":"Flight 1 → 3 is tried next. What happens to the $500 under city 3 in row 2?","options":[{"id":"replaced","label":"It becomes $400","rationale":"Row 1 has city 1 at $100, so the flight offers $100 + $300 = $400. That is cheaper than $500, so it is written.","isCorrect":true},{"id":"kept","label":"It stays $500","rationale":"$500 was copied down as the best price within one flight. A cheaper offer replaces it, so work out what flight 1 → 3 offers.","isCorrect":false},{"id":"added","label":"It becomes $800","rationale":"The flight's price is added to its starting city's price, the $100 under city 1. The $500 under city 3 is only what the new total is compared against.","isCorrect":false}]},{"id":"read-answer","title":"Flights 0 → 1 and 0 → 3 offer nothing cheaper, and every row is filled. Which cell is the answer for at most 1 stop from city 0 to city 3?","options":[{"id":"last-row","label":"Row 2 under city 3: $400","rationale":"One stop allows two flights, and row 2 holds the cheapest prices within two flights. City 3 is the destination, and $400 is the trip worked out by hand on the map, 0 → 1 → 3.","isCorrect":true},{"id":"row-k","label":"Row 1 under city 3: $500","rationale":"Row 1 allows one flight, which is zero stops. The stop limit is 1, so the row to read is 1 + 1 = 2.","isCorrect":false},{"id":"row-minimum","label":"The lowest price in row 2: $0","rationale":"$0 is the price of staying in city 0. The trip has to end in city 3, so only that column counts.","isCorrect":false}]}]},{"id":"one-row-shortcut","kind":"info","title":"Each row was built from the row above it and nothing else","workspacePanel":"visualizer","body":["Every offer in row 2 started from a price in row 1, and row 0 was not looked at again once row 1 was done. Keeping every row then looks like wasted memory."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"finished-table","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,400]],"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"snapshot-pitfall","kind":"pitfall","title":"Can a single row, updated in place, replace the table?","summary":"The code keeps one row of prices, `cost`, and makes `k + 1` passes over the flights. Every flight reads its starting city's price from that row and writes its offer back into the same row.","workspacePanel":"trace","pitfall":"The code below keeps a single row of prices that every flight both reads and writes.","whyItMatters":"A price written early in a pass was read later in the same pass, so one pass added three flights to a trip. In the table that cannot happen: while a row is being written, the row it reads from stays as it was.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"INF = 1000000000\ncost = [INF] * n\ncost[src] = 0\nfor _ in range(k + 1):\n    for a, b, price in flights:\n        if cost[a] == INF:\n            continue\n        if cost[a] + price < cost[b]:\n            cost[b] = cost[a] + price\nanswer = cost[dst]","steps":[{"id":"seed-row","title":"The row starts as row 0 did","codeLine":3,"summary":"City 0 is at $0 and every other city at ∞. The stop limit is 1, so two passes over the flights are coming.","state":{"arrays":[{"name":"cost","values":[0,"∞","∞","∞"],"current":0}]}},{"id":"fire-0-1","title":"Flight 0 → 1 writes $100","codeLine":9,"summary":"First pass, first flight: $0 + $100 = $100 goes under city 1, in the same row the next flights will read.","state":{"arrays":[{"name":"cost","values":[0,100,"∞","∞"],"current":1}]}},{"id":"fire-1-2","title":"Flight 1 → 2 reads the $100 just written","codeLine":9,"summary":"This is still the first pass. City 1 now shows $100, so the flight writes $100 + $100 = $200 under city 2, the price of a two-flight trip.","state":{"arrays":[{"name":"cost","values":[0,100,200,"∞"],"current":2}]}},{"id":"fire-2-3","title":"Flight 2 → 3 chains a third flight","codeLine":9,"summary":"City 2 shows $200, so city 3 gets $200 + $100 = $300. One pass has built a three-flight trip.","state":{"arrays":[{"name":"cost","values":[0,100,200,300],"current":3}]}},{"id":"wrong-answer","title":"It returns $300 for a trip limited to 1 stop","codeLine":10,"summary":"The remaining flights offer $400 and $500 for city 3, and the second pass changes nothing, so the price under city 3 stays $300. That trip makes two stops. The cheapest trip within the limit costs $400.","state":{"arrays":[{"name":"cost","values":[0,100,200,300],"current":3}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const INF = 1000000000;\nconst cost = Array.from({ length: n }, () => INF);\ncost[src] = 0;\nfor (let i = 0; i < (k + 1); i++) {\n    for (const [a, b, price] of flights) {\n        if (cost[a] === INF) {\n            continue;\n        }\n        if ((cost[a] + price) < cost[b]) {\n            cost[b] = (cost[a] + price);\n        }\n    }\n}\nconst answer = cost[dst];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":14},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const INF = 1000000000;\nconst cost = Array.from({ length: n }, () => INF);\ncost[src] = 0;\nfor (let i = 0; i < (k + 1); i++) {\n    for (const [a, b, price] of flights) {\n        if (cost[a] === INF) {\n            continue;\n        }\n        if ((cost[a] + price) < cost[b]) {\n            cost[b] = (cost[a] + price);\n        }\n    }\n}\nconst answer = cost[dst];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":14},"statementBundles":{"7":{"startLine":7,"endLine":8},"9":{"startLine":10,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int INF = 1000000000;\nList<Integer> cost = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    cost.add(INF);\n}\ncost.set(src, 0);\nfor (int i = 0; i < (k + 1); i++) {\n    for (List<Integer> flight : flights) {\n        int a = flight.get(0);\n        int b = flight.get(1);\n        int price = flight.get(2);\n        if (cost.get(a) == INF) {\n            continue;\n        }\n        if ((cost.get(a) + price) < cost.get(b)) {\n            cost.set(b, (cost.get(a) + price));\n        }\n    }\n}\nint answer = cost.get(dst);","lineMap":{"1":1,"2":2,"3":6,"4":7,"5":8,"6":12,"7":13,"8":15,"9":16,"10":20},"statementBundles":{"2":{"startLine":2,"endLine":5},"5":{"startLine":8,"endLine":11},"7":{"startLine":13,"endLine":14},"9":{"startLine":16,"endLine":19}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int INF = 1000000000;\nList<int> cost = Enumerable.Range(0, n).Select(_ => INF).ToList();\ncost[src] = 0;\nfor (int i = 0; i < k + 1; i++) {\n    foreach (var item in flights) {\n        int a = item[0];\n        int b = item[1];\n        int price = item[2];\n        if (cost[a] == INF) {\n            continue;\n        }\n        if (cost[a] + price < cost[b]) {\n            cost[b] = cost[a] + price;\n        }\n    }\n}\nint answer = cost[dst];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9,"7":10,"8":12,"9":13,"10":17},"statementBundles":{"5":{"startLine":5,"endLine":8},"7":{"startLine":10,"endLine":11},"9":{"startLine":13,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int INF = 1000000000;\nvector<int> cost = vector<int>(n, INF);\ncost[src] = 0;\nfor (int i = 0; i < (k + 1); i++) {\n    for (vector<int> item : flights) {\n        int a = item[0];\n        int b = item[1];\n        int price = item[2];\n        if (cost[a] == INF) {\n            continue;\n        }\n        if ((cost[a] + price) < cost[b]) {\n            cost[b] = (cost[a] + price);\n        }\n    }\n}\nint answer = cost[dst];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":9,"7":10,"8":12,"9":13,"10":17},"statementBundles":{"5":{"startLine":5,"endLine":8},"7":{"startLine":10,"endLine":11},"9":{"startLine":13,"endLine":16}}}}}},{"id":"edge-case-intro","kind":"info","title":"The table answered a limit of 1 stop. Next, two other limits on the same map.","workspacePanel":"visualizer","body":["First, no stops at all. Then three stops, more than any trip on this map makes. Does the same table give the right answer for both?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"finished-table","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,400]],"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"unreachable-edge","kind":"case-probe","title":"First, no stops are allowed, and the destination is city 2. What should the function return?","workspacePanel":"visualizer","options":[{"id":"minus-one","label":"-1, because row 1 has ∞ under city 2","rationale":"No stops means one flight, so row 1 is the last row. Its ∞ under city 2 says no trip fits, and the answer for that is -1.","isCorrect":true},{"id":"two-flights","label":"$200, the price of 0 → 1 → 2","rationale":"That trip stops in city 1. With no stops allowed there are only rows 0 and 1, and neither has a price for city 2.","isCorrect":false},{"id":"placeholder","label":"The large number that stands in for ∞","rationale":"That number only marks cells no trip has reached. Returning it would report a price nobody can pay.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-stops","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"spare-flights","kind":"case-probe","title":"Then a limit of 3 stops. Row 4 is now the last row, but no trip on this map uses four flights. What ends up under city 3 in row 4?","workspacePanel":"visualizer","options":[{"id":"copied","label":"$300, copied down from row 3","rationale":"Row 4 starts as a copy of row 3, and no flight offers city 3 anything cheaper. The three-flight trip is still within a limit of four, so every limit of 2 stops or more returns $300.","isCorrect":true},{"id":"no-trip","label":"∞, since no trip uses exactly four flights","rationale":"A row holds trips with at most that many flights. If row 4 kept only four-flight trips, the function would return -1 while a $300 trip is allowed.","isCorrect":false},{"id":"cheaper-again","label":"$200, one step cheaper than row 3","rationale":"A price drops only when some flight offers less. The cheapest trip to city 3 on this map costs $300, however many flights are allowed.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-stops","state":{"grid":[[0,"∞","∞","∞"],[0,100,"∞",500],[0,100,200,400],[0,100,200,300],["∞","∞","∞","∞"]],"r":4,"c":3,"filled":[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3],[3,0],[3,1],[3,2],[3,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"ready-to-code","kind":"info","title":"Build every row from the finished row above","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function builds a table with one column per city and one row per flight limit, rows 0 through one more than the stop limit. Every cell starts at ∞, and the starting city is $0 in row 0.","Each new row starts as a copy of the row above. Then every flight offers its starting city's price from the row above plus its own price, and the arriving city keeps the cheaper price.","After the last row is filled, the function returns the destination's price there, or -1 if it is still ∞."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seeded","state":{"grid":[[0,"∞","∞","∞"],["∞","∞","∞","∞"],["∞","∞","∞","∞"]],"filled":[[0,0],[0,1],[0,2],[0,3]],"changed":[],"labels":{"grid":"cheapest price"},"colLabels":["city 0","city 1","city 2","city 3"],"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,100],[1,2,100],[2,3,100],[1,3,300],[0,3,500]]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Build the price table in code","workspacePanel":"code","checkpoints":[{"id":"init-stop-table","title":"Create the table and set the starting cell","description":"Make a table with a row for every flight limit from 0 to `k + 1` and a column for every city. Fill it with a no-trip value larger than any real total, then set the starting city to 0 in row 0.","commonMistakes":["Making `k + 1` rows, which leaves no row for a trip that uses all `k + 1` flights","Leaving the starting city at the no-trip value in row 0, so no flight ever has a trip to extend"],"hint":"`k` stops allow `k + 1` flights, and row 0 is one more row on top of those.","semanticSpec":{"intent":"Initialize bounded Bellman-Ford price state before any flight relaxation.","doneWhen":"The solution creates a stop-layered price table sized by allowed edge count and city count, fills unreachable entries with an INF-like sentinel, and sets the source city in layer 0 to price 0 before relaxation starts.","shouldFailWhen":"This step should fail if the price state is not indexed by both stop layer and city, if the source is not seeded at layer 0, or if the table is allocated inside the relaxation loop.","roles":["price table","stop layer","city index","source city","unreachable sentinel"],"mustProve":["The price state has separate storage for each allowed edge count from 0 through k + 1.","Each stop layer contains per-city price entries.","The source city starts at price 0 in the zero-edge layer before the flight loops."],"mustNotAccept":["A scalar price value with no per-city indexed state.","A single shared city-price row reused for every stop layer.","A table allocated inside the flight relaxation loop.","A layered table where the source is never seeded to 0 before relaxation."],"equivalentVariants":["Use a 2D list, array, or equivalent indexed table for stop layers and cities.","Use an equivalent layer-indexed distance representation as long as layer 0 records only the source as reachable."],"proofSnippets":[{"id":"py-cheapest-flights-init-stop-table","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-stop-table","readMode":"graph-value-query-v1"}]}},{"id":"carry-forward","title":"Copy each row down before trying flights","description":"For each flight limit in turn, carry the prices of the current row into the next row before any flight is tried. A trip that fits in fewer flights still fits the larger limit.","commonMistakes":["Filling the next row only where a flight lands, which drops cheaper trips that use fewer flights"],"hint":"Without the copy, a city that no flight improves falls back to the no-trip value in the next row.","semanticSpec":{"intent":"Propagate indexed price state from one stop layer to the next.","doneWhen":"This step is done when each next-layer row starts from a distinct previous-layer snapshot before relaxation, so carry-forward prices are preserved without allowing in-place chaining inside the same pass.","shouldFailWhen":"This step should fail if the table is initialized but no indexed state is carried forward.","roles":["price table","current stop layer","next stop layer","city index"],"mustProve":["The next layer is distinct from the previous layer.","Known prices from the previous layer are available before flight relaxations in the next layer.","Writes for the current pass do not change the source state used by other flights in that same pass."],"mustNotAccept":["A table allocation with no carry-forward loop.","A loop that overwrites the next layer without reading the previous layer."],"equivalentVariants":["Copy a full row before relaxing flights.","Conditionally write each previous-layer price into the next layer."],"proofSnippets":[{"id":"py-cheapest-flights-carry-forward","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"carries_forward_indexed_numeric_state","scope":"carry-forward","readMode":"numeric-state-value-query-v1"}]}},{"id":"compute-candidates","title":"Work out what each flight offers","description":"For every flight, take its starting city's price in the current row and add the flight's price. A flight whose starting city has no trip yet has nothing to offer and is skipped.","commonMistakes":["Reading the starting city's price from the row being filled, which lets one pass chain several flights","Adding the flight's price to the arriving city's price instead of the starting city's"],"hint":"The starting price comes from the row that is already finished, never from the row being filled.","semanticSpec":{"intent":"Build weighted relaxation candidates from flight entries and previous-layer prices.","doneWhen":"The solution repeatedly scans flights, binds source/destination/cost roles, and compares a weighted candidate against the destination price.","shouldFailWhen":"This step should fail if flights are scanned without computing a source-price-plus-cost candidate.","roles":["flight edge","source city","destination city","flight cost","candidate price"],"mustProve":["Flight entries are destructured into source, destination, and weight roles.","A candidate price combines the prior source price with the flight cost."],"mustNotAccept":["A loop over flights that ignores the flight cost.","A candidate based on the destination price instead of the source price."],"equivalentVariants":["Store the candidate in a local variable before comparing.","Compute the candidate inline in the cheaper-price guard."],"proofSnippets":[{"id":"py-cheapest-flights-compute-candidates","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                pass"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"computes_weighted_edge_relaxation_candidate","scope":"relax-candidate","readMode":"graph-value-query-v1"}]}},{"id":"relax-flights","title":"Keep the cheaper price","description":"Compare each flight's offer with the price already under its arriving city in the next row, and write the offer when it is lower.","commonMistakes":["Writing every offer without comparing, so a costlier flight later in the list overwrites a cheaper price"],"hint":"The copied-down price and every flight into the same city compete for one cell, and the lowest stays.","semanticSpec":{"intent":"Perform bounded Bellman-Ford relaxation over all flights.","doneWhen":"The solution repeats passes over the flight list and writes improved prices into the next stop layer.","shouldFailWhen":"This step should fail if there is no repeated relation pass or no weighted metric write.","roles":["flight edge","source city","destination city","price table","candidate price"],"mustProve":["The solution loops over relation entries from flights.","A candidate price combines a previous source price with the flight cost.","The destination price state is updated when the candidate is cheaper."],"mustNotAccept":["A single direct-flight lookup without repeated passes.","A loop that scans flights but never updates distance or price state."],"equivalentVariants":["Use a 2D DP table by edge count.","Use another layer-separated representation as long as each pass reads the prior layer and writes the next layer."],"proofSnippets":[{"id":"py-cheapest-flights-relax-layers","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                dp[step + 1][v] = candidate"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"relax-all-edges","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return the price in the last row","description":"Once every row is filled, read the destination's cell in row `k + 1`. Return it, or -1 if it still holds the no-trip value.","commonMistakes":["Reading row `k`, which allows one flight fewer than the limit","Returning the no-trip value itself when the destination was never reached"],"hint":"The last row is the one that allows `k + 1` flights.","semanticSpec":{"intent":"Return the terminal result from the completed weighted relaxation state.","doneWhen":"The solution reads the final destination price after all relaxation rounds and returns that terminal result.","shouldFailWhen":"This step should fail if the relaxation result is never returned.","roles":["final layer","destination city","unreachable sentinel","terminal answer"],"mustProve":["The terminal result is returned after bounded relaxation has completed."],"mustNotAccept":["Returning a loop counter or unrelated scalar.","Returning before all allowed relaxation passes have completed."],"equivalentVariants":["Store the final destination value in a variable before returning it.","Return the final destination table entry directly after checking the sentinel."],"proofSnippets":[{"id":"py-cheapest-flights-return-result","language":"python","code":"def findCheapestPrice(n, flights, src, dst, k):\n    INF = 10**15\n    dp = [[INF] * n for _ in range(k + 2)]\n    dp[0][src] = 0\n    for step in range(k + 1):\n        for node in range(n):\n            if dp[step][node] < dp[step + 1][node]:\n                dp[step + 1][node] = dp[step][node]\n        for u, v, cost in flights:\n            if dp[step][u] == INF:\n                continue\n            candidate = dp[step][u] + cost\n            if candidate < dp[step + 1][v]:\n                dp[step + 1][v] = candidate\n    answer = dp[k + 1][dst]\n    if answer == INF:\n        return -1\n    return answer"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_relaxed_metric_result","scope":"return-result","readMode":"graph-value-query-v1"}]}}]},{"id":"complete","kind":"complete","title":"Cheapest price by flight limit, one row at a time","workspacePanel":"code","takeaways":[{"title":"One price per city and flight limit","body":"The cheapest price to a city depends on how many flights are allowed, so row r holds each city's cheapest price using at most r flights. The answer is the destination's cell in row `k + 1`, or -1 when that cell is still ∞."},{"title":"Each row comes from the row above","body":"A row starts as a copy of the row above. Then every flight offers its starting city's price from the row above plus its own price, and the cheaper price stays. Reading from the row being filled instead would let one pass chain several flights."},{"title":"Time O((k + 1) · (n + f)), space O((k + 2) · n)","body":"With f flights, each of the `k + 1` passes copies n prices and tries every flight once. The table has `(k + 2) · n` cells, and because a row reads only the row above, keeping two rows would bring the space down to O(n)."}]}],"slidesOrigin":"authored"}}
