{"id":"network-delay-time","title":"Network Delay Time","difficulty":"medium","patterns":["heap"],"primaryConcept":"graph-shortest-path-negative","concepts":["graph-shortest-path-negative"],"problemForm":"core","companies":["Amazon","Google","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"weighted-graph-edges","primaryParam":"times","sizeMetric":"nodes-plus-edges","constraints":["1-indexed","positive"],"valueRange":{"min":1,"max":100},"secondaryParams":{"n":{"strategy":"scale-with-primary"},"k":{"strategy":"fixed","value":1}}},"description":"You are given a directed weighted network with `n` nodes labeled from `1` to `n`. Each edge `times[i] = [u, v, w]` means a signal takes `w` time to travel from `u` to `v`.\n\nReturn how long it takes for a signal sent from node `k` to reach every node. If any node cannot be reached, return `-1`.","examples":[{"input":"times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2","output":"2","explanation":"The signal reaches node 1 and node 3 in 1 time, then node 4 in 2 time."},{"input":"times = [[1,2,1]], n = 2, k = 2","output":"-1","explanation":"Node 1 is not reachable from node 2."}],"constraints":[{"id":"1-n-100","text":"1 <= n <= 100","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":100}},{"id":"1-k-n","text":"1 <= k <= n","check":{"kind":"valueRange","target":"k","selector":"value","min":1,"max":{"valueOfInput":"n"}}},{"id":"0-len-times-6000","text":"0 <= len(times) <= 6000","check":{"kind":"sizeRange","target":"times","measure":"arrayLength","min":0,"max":6000}},{"id":"each-edge-is-u-v-w","text":"Each edge is [u, v, w]","check":{"kind":"shape","target":"times","shape":"tupleArray","tupleLength":3}},{"id":"1-u-v-n","text":"1 <= u, v <= n","check":[{"kind":"valueRange","target":"times","selector":"tupleItemsAtIndex","index":0,"min":1,"max":{"valueOfInput":"n"}},{"kind":"valueRange","target":"times","selector":"tupleItemsAtIndex","index":1,"min":1,"max":{"valueOfInput":"n"}}]},{"id":"1-w-100","text":"1 <= w <= 100","check":{"kind":"valueRange","target":"times","selector":"tupleItemsAtIndex","index":2,"min":1,"max":100}}],"starterCode":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        # Your code here\n        pass","functionName":"networkDelayTime","testCases":[{"id":"1","input":{"times":[[2,1,1],[2,3,1],[3,4,1]],"n":4,"k":2},"expected":2,"description":"Canonical directed network."},{"id":"2","input":{"times":[[1,2,1]],"n":2,"k":1},"expected":1,"description":"Single reachable edge."},{"id":"3","input":{"times":[[1,2,1]],"n":2,"k":2},"expected":-1,"description":"The source cannot reach every node."},{"id":"4","input":{"times":[],"n":1,"k":1},"expected":0,"description":"A single node receives the signal immediately."},{"id":"5","input":{"times":[[1,2,2],[1,3,5],[2,3,1],[3,4,2]],"n":4,"k":1},"expected":5,"description":"A cheaper indirect path improves an earlier distance."},{"id":"h1","input":{"times":[[1,2,1],[2,3,2]],"n":3,"k":1},"description":"A simple directed chain accumulates delay along the path.","expected":3},{"id":"h2","input":{"times":[[1,2,1],[2,3,2]],"n":4,"k":1},"description":"An unreachable node makes the answer impossible.","expected":-1},{"id":"h3","input":{"times":[[1,2,1],[2,4,2],[1,3,4],[3,4,1]],"n":4,"k":1},"description":"A shorter indirect route beats the direct path to one node.","expected":4},{"id":"h4","input":{"times":[[3,1,4],[3,2,2],[2,4,2],[4,5,1]],"n":5,"k":3},"description":"The source sits in the middle of the graph.","expected":5},{"id":"h5","input":{"times":[[2,1,1],[2,3,1],[3,4,1],[1,4,5]],"n":4,"k":2},"description":"Multiple routes converge on the last node.","expected":2},{"id":"topup-unreachable-node","input":{"times":[[1,2,5],[2,3,5]],"n":4,"k":1},"expected":-1,"description":"An unreachable node makes the delay impossible."},{"id":"topup-better-indirect-route","input":{"times":[[1,2,10],[1,3,2],[3,2,1],[2,4,3]],"n":4,"k":1},"expected":6,"description":"An indirect route beats a direct slower edge."}],"hints":[{"level":1,"content":"Track the best known arrival time for every node."},{"level":2,"content":"Repeatedly relax every directed edge so shorter paths can propagate through the network."},{"level":3,"content":"If any distance is still infinite after relaxation, some node is unreachable."}],"guidedFlow":{"version":2,"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":"plain-bfs","name":"Plain BFS","summary":"Spread the signal in queue order and lock each node the first time it is reached.","decisionReason":"BFS counts hops, so it freezes a node at its first arrival and never lets a cheaper many-hop route lower it. With weighted edges that returns the wrong delay.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time but ignores edge weights, so it commits to the fewest-hop path instead of the fastest one."],"isOptimal":false},{"id":"closest-first-settling","name":"Closest-first settling","summary":"Keep a tentative time per node, settle the smallest unvisited one as final, and relax its outgoing edges so neighbors can still improve.","decisionReason":"Settling the closest unvisited node first is exactly what lets a cheaper route lower a node before it is locked, so every settled time is the true fastest arrival.","complexity":{"time":"O((n + e) log n)","space":"O(n + e)"},"tradeoffs":["A heap keeps the next-closest node cheap to find, so the work is about O((n + e) log n)."],"isOptimal":true}]},"codingCheckpoints":[{"id":"build-adjacency","title":"Build weighted adjacency","description":"Convert 1-indexed edges into a zero-based adjacency list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"builds_projected_result_sequence","scope":"convert-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Normalize the 1-indexed edge list into adjacency entries that can be used with zero-based distance indices.","doneWhen":"This step is done when every directed edge contributes a zero-based destination and weight under its zero-based source node.","shouldFailWhen":"This step should fail if the code indexes adjacency or distances with raw 1-indexed node labels.","roles":["weighted adjacency list","source label","zero-based endpoints"],"mustProve":["The implementation derives adjacency entries from `times`.","Both edge endpoints are shifted before they are used as array indices."],"mustNotAccept":["Subtracting one from only one endpoint.","Using raw input labels directly as adjacency or distance indices."],"equivalentVariants":["Append `(v - 1, w)` into `adj[u - 1]`.","First normalize edge triples, then populate adjacency from them."],"proofSnippets":[{"id":"py-network-delay-time-build-adjacency","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        source = k - 1\n        return len(adj) + source"}]},"commonMistakes":["Mixing 1-indexed input labels with zero-based arrays","Normalizing k but not the edge endpoints"],"hint":"Choose one indexing scheme before building adjacency or seeding the source."},{"id":"init-dist","title":"Initialize distances","description":"Create the distance array and seed only the source node to 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-dist","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize weighted shortest-path state so only the source starts reachable.","doneWhen":"This step is done when the code creates a length-n distance array filled with an infinity sentinel and writes 0 at the normalized source index before relaxation.","shouldFailWhen":"This step should fail if every node starts at 0 or if the source is not seeded before the heap loop.","roles":["distance array","infinity sentinel","source seed"],"mustProve":["The distance structure covers every node.","The source has distance 0 before closest-first relaxation starts.","Non-source nodes remain at the unreachable sentinel initially."],"mustNotAccept":["Initializing all nodes as reachable.","Seeding the source after the heap loop."],"equivalentVariants":["Use any large sentinel or infinity value.","Use any array-like distance container with one slot per node."],"proofSnippets":[{"id":"py-network-delay-time-init-dist","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n        return dist[source]"}]},"commonMistakes":["Starting all distances at 0","Forgetting to convert k before seeding the source"],"hint":"Everything starts unreachable except the source."},{"id":"closest-first-relaxation","title":"Relax from the closest node","description":"Use a min-heap to pop the closest tentative node and relax its outgoing edges.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"pushes_heap_values","scope":"heap-push"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop"}]}]},"semanticSpec":{"intent":"Drive weighted relaxation by the smallest tentative arrival time instead of scanning every edge in fixed rounds.","doneWhen":"This step is done when the code pushes tentative arrivals into a heap, pops the smallest one, skips stale entries, and pushes improved neighbor distances.","shouldFailWhen":"This step should fail if the code uses plain queue order, scans edges only once, or updates neighbors without a closest-first priority structure.","roles":["min-heap frontier","closest tentative node","stale-entry guard","distance update"],"mustProve":["Tentative arrivals are inserted into a priority heap.","The loop extracts the next closest tentative arrival from that heap.","Improved neighbor distances are returned to the heap for later settling."],"mustNotAccept":["Using a FIFO queue for weighted shortest paths.","Relaxing a neighbor without comparing against its current best distance."],"equivalentVariants":["Use stale-entry skipping with `time != dist[u]`.","Use an explicit settled set after the heap pop."],"proofSnippets":[{"id":"py-network-delay-time-closest-first-relaxation","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        import heapq\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n        heap = []\n        heapq.heappush(heap, (0, source))\n        while heap:\n            time, u = heapq.heappop(heap)\n            if time != dist[u]:\n                continue\n            for v, w in adj[u]:\n                cand = time + w\n                if cand < dist[v]:\n                    dist[v] = cand\n                    heapq.heappush(heap, (cand, v))"}]},"commonMistakes":["Using discovery order instead of distance order","Forgetting to push an improved neighbor back into the heap"],"hint":"The heap should hold `(arrival_time, node)` candidates."},{"id":"return-delay","title":"Return final delay","description":"Reject unreachable nodes and return the maximum finite shortest distance.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_scan_decision","scope":"return-result","readMode":"array-scan-value-query-v1"}]}]},"semanticSpec":{"intent":"Convert the settled distance state into the required network delay answer.","doneWhen":"This step is done when the code returns -1 if any node remains unreachable and otherwise returns the maximum distance in the final distance array.","shouldFailWhen":"This step should fail if max distance is returned while an infinite distance remains, or if the return is not based on the slowest final arrival.","roles":["final distance array","unreachable sentinel","maximum finite distance"],"mustProve":["The code checks for unreachable nodes after relaxation.","The valid return value is derived from the maximum final distance."],"mustNotAccept":["Returning the source distance.","Returning max(dist) without guarding unreachable nodes."],"equivalentVariants":["Compute `delay = max(dist)` and compare it with the sentinel.","Scan distances once, returning -1 on an unreachable entry and tracking the maximum finite distance."],"proofSnippets":[{"id":"py-network-delay-time-return-delay","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        import heapq\n\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n\n        heap = []\n        heapq.heappush(heap, (0, source))\n        while heap:\n            time, u = heapq.heappop(heap)\n            if time != dist[u]:\n                continue\n            for v, w in adj[u]:\n                cand = time + w\n                if cand < dist[v]:\n                    dist[v] = cand\n                    heapq.heappush(heap, (cand, v))\n\n        delay = max(dist)\n        if delay == INF:\n            return -1\n        return int(delay)\n"}]},"commonMistakes":["Returning the source distance instead of the farthest reachable distance","Treating an unreachable node as a very large answer"],"hint":"The signal finishes when the slowest reachable node receives it."}],"slides":[{"id":"read-the-signal","chapter":"The network","kind":"info","eyebrow":"Read the problem","title":"How long until the signal reaches everyone?","workspacePanel":"problem","body":["You are given a directed network of nodes numbered 1 to n. Each edge [u, v, w] means a signal takes w time to travel from u to v. A signal starts at node k. You report how long it takes to reach every node, or -1 if some node never gets it.","A signal can reach a node along several routes, and the time that counts is the fastest one. The whole network is done only when its slowest node finally hears the signal, so the answer is the largest of those fastest arrival times."]},{"id":"naive-bfs","chapter":"The obvious way","kind":"code-trace","source":"brute-force","eyebrow":"Start naive","title":"Spread the signal hop by hop","summary":"A direct plan treats the network like an unweighted one: walk outward from the source, and the first time a node is discovered, record the arrival time along the path that found it. Watch which path it commits to for node 3.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"INF = 10 ** 9\nsource = k - 1\narrival = [INF, INF, INF, INF, INF]\narrival[source] = 0\nqueue.append(source)\nwhile queue:\n    u = queue.popleft()\n    for v, w in adj[u]:\n        if arrival[v] == INF:\n            arrival[v] = arrival[u] + w\n            queue.append(v)\nreturn arrival[4]","typeContext":{"symbols":{"adj":{"kind":"list","item":{"kind":"list","item":{"kind":"list","item":"int"}}},"queue":{"kind":"list","item":"int"}}},"steps":[{"id":"bfs-source","title":"Start the signal at node 1","codeLine":5,"summary":"Node 1 arrives at time 0 and goes into the queue. Every other node is still at ∞.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[]},"arrays":[{"name":"dist","values":[0,"∞","∞","∞","∞"],"current":0}]}},{"id":"bfs-hop1","title":"Hop 1 discovers nodes 2 and 3 directly","codeLine":10,"summary":"From node 1, both 1→2 and 1→3 are one hop away. Node 2 records 2 and node 3 records 7 from the direct edge, because that is the path that discovered it first.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[],"highlighted":[3],"activeEdges":[[1,3]]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":2}]}},{"id":"bfs-hop2","title":"Hop 2 commits node 4 through node 2","codeLine":10,"summary":"Node 2 hands the signal to node 4 along 2→4, recording 2 + 8 = 10. Node 3 was already discovered, so its leftover edge 2→3 is ignored.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":2,"visited":[1],"highlighted":[4],"activeEdges":[[2,4]]},"arrays":[{"name":"dist","values":[0,2,7,10,"∞"],"current":3}]}},{"id":"bfs-done","title":"It returns 12, but the real answer is 8","codeLine":12,"summary":"Node 5 lands at 10 + 2 = 12, so this hands back 12. The signal actually reaches every node in 8, so the hop-by-hop walk has overshot somewhere along the way.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":5,"visited":[1,2,3,4]},"arrays":[{"name":"dist","values":[0,2,7,10,12],"current":4}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const INF = (10 ** 9);\nconst source = k - 1;\nconst arrival = [INF, INF, INF, INF, INF];\narrival[source] = 0;\nqueue.push(source);\nwhile (queue.length > 0) {\n    const u = queue.shift();\n    for (const [v, w] of adj[u]) {\n        if (arrival[v] === INF) {\n            arrival[v] = (arrival[u] + w);\n            queue.push(v);\n        }\n    }\n}\nreturn arrival[4];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":15},"statementBundles":{"11":{"startLine":11,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const INF = (10 ** 9);\nconst source = k - 1;\nconst arrival = [INF, INF, INF, INF, INF];\narrival[source] = 0;\nqueue.push(source);\nwhile (queue.length > 0) {\n    const u = queue.shift()!;\n    for (const [v, w] of adj[u]) {\n        if (arrival[v] === INF) {\n            arrival[v] = (arrival[u] + w);\n            queue.push(v);\n        }\n    }\n}\nreturn arrival[4];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":15},"statementBundles":{"11":{"startLine":11,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int INF = 1000000000;\nint source = k - 1;\nList<Integer> arrival = new ArrayList<>(List.of(INF, INF, INF, INF, INF));\narrival.set(source, 0);\nqueue.add(source);\nwhile (!queue.isEmpty()) {\n    int u = queue.remove(0);\n    for (List<Integer> item : adj.get(u)) {\n        int v = item.get(0);\n        int w = item.get(1);\n        if (arrival.get(v) == INF) {\n            arrival.set(v, (arrival.get(u) + w));\n            queue.add(v);\n        }\n    }\n}\nreturn arrival.get(4);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":13,"12":17},"statementBundles":{"8":{"startLine":8,"endLine":10},"11":{"startLine":13,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int INF = 1000000000;\nint source = k - 1;\nList<int> arrival = new() { INF, INF, INF, INF, INF };\narrival[source] = 0;\nqueue.Add(source);\nwhile (queue.Count > 0) {\n    int u = queue[0];\n    queue.RemoveAt(0);\n    foreach (var item in adj[u]) {\n        int v = item[0];\n        int w = item[1];\n        if (arrival[v] == INF) {\n            arrival[v] = arrival[u] + w;\n            queue.Add(v);\n        }\n    }\n}\nreturn arrival[4];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":12,"10":13,"11":14,"12":18},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":11},"11":{"startLine":14,"endLine":17}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int INF = 1000000000;\nint source = k - 1;\nvector<int> arrival{INF, INF, INF, INF, INF};\narrival[source] = 0;\nqueue.push_back(source);\nwhile (!queue.empty()) {\n    int u = popFront(queue);\n    for (vector<int> item : adj[u]) {\n        int v = item[0];\n        int w = item[1];\n        if (arrival[v] == INF) {\n            arrival[v] = (arrival[u] + w);\n            queue.push_back(v);\n        }\n    }\n}\nreturn arrival[4];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":11,"10":12,"11":13,"12":17},"statementBundles":{"8":{"startLine":8,"endLine":10},"11":{"startLine":13,"endLine":16}}}}}},{"id":"why-it-fails","chapter":"The obvious way","kind":"case-probe","eyebrow":"Feel the gap","title":"Why does the hop-by-hop answer come out too large?","summary":"Node 3 sits one hop from the source along 1→3 with weight 7, and two hops away along 1→2→3 with total weight 5.","workspacePanel":"trace","options":[{"id":"fewest-hops","label":"It keeps the fewest-hops path, even when a longer path is faster","rationale":"Discovering node 3 in one hop locks its time at 7, so the 5-time route through node 2 never gets to replace it. Fewest hops is not the same as fastest time once edges carry weights.","isCorrect":true},{"id":"wrong-start","label":"It starts the signal at the wrong node","rationale":"The signal starts at node 1, which is correct. The error is in which path it trusts for each node, not where it begins.","isCorrect":false},{"id":"misses-edges","label":"It never looks at the edge 2→3","rationale":"It does scan 2→3, but by then node 3 already counts as discovered, so the cheaper time is thrown away. Scanning the edge is not enough; the time has to be allowed to improve.","isCorrect":false}],"answer":"It keeps the fewest-hops path. Node 3 locks at 7 from the one-hop edge, so the faster 5-time route through node 2 can never overwrite it."},{"id":"idea-bridge","chapter":"The idea","kind":"info","eyebrow":"Change the rule","title":"Let a slower route win when it is cheaper","workspacePanel":"visualizer","body":["The hop-by-hop walk failed because it froze each node the moment it was first reached, so a cheaper route that arrives in more hops never got to replace it. A correct method has to let a tentative time keep falling until it is safe to lock.","Start from node 1, settled at 0. Its two edges give node 2 a tentative 2 and node 3 a tentative 7, and every other node is still ∞. The next question is which of these tentative times we are allowed to trust as final."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"idea-bridge-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[1]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":0}]}}]}},{"id":"discover-closest-first","chapter":"The idea","kind":"case-probe","eyebrow":"Find the order","title":"Which unvisited node can be settled as final right now?","summary":"Only node 1 is settled, and the rest hold tentative times that later edges might still lower.","workspacePanel":"visualizer","options":[{"id":"smallest-tentative","label":"Node 2, the unvisited node with the smallest tentative time","rationale":"Every other unvisited node already needs at least 7 to be reached, and each remaining edge only adds time. So nothing can ever reach node 2 faster than its current 2, and that 2 is final.","isCorrect":true},{"id":"direct-from-source","label":"Node 3, because it has a direct edge from the source","rationale":"A direct edge does not make a node final. Node 3 is tentatively 7, but the route 1→2→3 will lower it to 5, so settling it now would lock in the wrong time.","isCorrect":false},{"id":"any-reachable","label":"Any node that now has a finite tentative time","rationale":"Node 4 and node 5 are still ∞, and even node 3 is not yet safe to settle. Only the smallest tentative time is guaranteed final this step.","isCorrect":false}],"answer":"Node 2. It holds the smallest tentative time, 2, and since every other path costs at least 7 already and edges only add time, nothing can beat it. That makes 2 final.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"discover-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[1],"highlighted":[2,3]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":1}]}}]}},{"id":"discover-relaxation","chapter":"The idea","kind":"case-probe","eyebrow":"Spread the gain","title":"After settling node 2 at time 2, what happens to node 3?","summary":"Node 2 is now final at 2 and has an outgoing edge 2→3 with weight 3. Node 3 currently holds 7 from the direct edge.","workspacePanel":"visualizer","options":[{"id":"improves-to-5","label":"Its tentative time drops to 5, the cheaper route through node 2","rationale":"Reaching node 3 through node 2 costs 2 + 3 = 5, which beats the direct 7. Settling the closest node and offering its time to each neighbor is exactly how the faster route replaces the slower one.","isCorrect":true},{"id":"stays-7","label":"It stays at 7, since it was already discovered","rationale":"That is the hop-by-hop mistake. A tentative time is allowed to improve: 5 is smaller than 7, so node 3 takes the 5.","isCorrect":false},{"id":"becomes-final","label":"It is settled as final at 7 before node 2 is checked","rationale":"Node 3 is not final yet. Only the closest unvisited node is settled, and offering node 2’s time first is what lets node 3 fall to 5 before it is ever settled.","isCorrect":false}],"answer":"It drops to 5. Reaching node 3 through the just-settled node 2 costs 2 + 3 = 5, which beats the direct 7, so node 3 takes the lower time.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"relax-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":2,"visited":[1,2],"highlighted":[3],"activeEdges":[[2,3]]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":2}]}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[1]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":0}]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it settle","title":"Settle the closest, relax its edges, repeat","workspacePanel":"visualizer","body":["The dist array holds the best-known time to each node. The source starts at 0 and everyone else at ∞. No node is settled yet.","Each round picks the unvisited node with the smallest tentative time, marks it final, and offers its time along each outgoing edge so neighbors can improve.","We will walk this on the network from node 1, settling one node per round until every node is final, then read off the largest time."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[]},"arrays":[{"name":"dist","values":[0,"∞","∞","∞","∞"],"current":0}]}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the settling","title":"Settle the network node by node","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"settle-2","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":2,"visited":[1,2],"highlighted":[3],"activeEdges":[[2,3]]},"arrays":[{"name":"dist","values":[0,2,7,"∞","∞"],"current":2}]}},{"id":"settle-3","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":3,"visited":[1,2,3],"highlighted":[4],"activeEdges":[[3,4]]},"arrays":[{"name":"dist","values":[0,2,5,10,"∞"],"current":3}]}},{"id":"settle-rest","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":5,"visited":[1,2,3,4,5]},"arrays":[{"name":"dist","values":[0,2,5,6,8],"current":4}]}}]},"beats":[{"id":"settle-2","title":"Settle node 2 at time 2. Which node does relaxing its edges improve?","summary":"Node 1 is final at 0. The smallest tentative time among the rest is node 2 at 2, so node 2 settles next.","prompt":"Node 2 offers its time 2 along 2→3 (weight 3) and 2→4 (weight 8).","options":[{"id":"node3-to-5","label":"Node 3 falls from 7 to 5","rationale":"2 + 3 = 5 beats node 3’s direct 7, so node 3 improves to 5. Node 4 also gets a first tentative 2 + 8 = 10. Node 3 is the one whose existing time improves.","isCorrect":true},{"id":"node4-final","label":"Node 4 becomes final at 10","rationale":"Node 4 gets a tentative 10 here and stays unsettled. Its 10 is not the smallest tentative time on the board, and a cheaper route through node 3 is still coming.","isCorrect":false},{"id":"nothing","label":"Nothing changes, node 3 keeps 7","rationale":"A tentative time improves whenever a cheaper route appears. The route through node 2 costs 5, which is less than 7, so node 3 must drop to 5.","isCorrect":false}],"answer":"Node 3 falls from 7 to 5, because 2 + 3 beats the direct 7. Node 4 also picks up a tentative 10 along the way."},{"id":"settle-3","title":"The smallest tentative time is now node 3 at 5. What does settling it do to node 4?","summary":"Nodes 1 and 2 are final. Among the rest, node 3 at 5 is smaller than node 4 at 10, so node 3 settles next.","prompt":"Node 3 offers its time 5 along 3→4 (weight 1).","options":[{"id":"node4-to-6","label":"Node 4 drops from 10 to 6","rationale":"5 + 1 = 6 beats node 4’s tentative 10, so node 4 improves to 6. The longer-hop route through node 3 wins because closest-first reached node 3 with the right time first.","isCorrect":true},{"id":"node4-stays-10","label":"Node 4 stays at 10, its first discovered time","rationale":"A tentative time is never frozen until the node is settled. 6 is cheaper than 10, so node 4 takes the 6.","isCorrect":false},{"id":"node5-now","label":"Node 5 gets a tentative time now","rationale":"Node 5 is only reachable from node 4, which is still tentative. Node 5 stays at ∞ until node 4 is settled.","isCorrect":false}],"answer":"Node 4 drops from 10 to 6, because 5 + 1 beats 10. The cheaper longer-hop route reaches node 4 once node 3 is settled with the correct time."},{"id":"settle-rest","title":"Now that every node is final, what is the network delay?","summary":"Settling finishes: node 4 at 6 relaxes 4→5 to 8, then node 5 settles last, and every node now holds its fastest arrival time.","prompt":"The signal has reached every node along its fastest route.","options":[{"id":"eight","label":"8","rationale":"The slowest node to hear the signal is node 5 at time 8, so the whole network is done at 8. The answer is the largest of the fastest arrival times.","isCorrect":true},{"id":"twentyone","label":"21","rationale":"Adding the times is not the answer. The signal reaches all nodes in parallel; the delay is the single slowest arrival, which is 8.","isCorrect":false},{"id":"two","label":"2","rationale":"2 is the fastest arrival, node 2. The delay is the slowest arrival, so it is node 5 at 8.","isCorrect":false}],"answer":"8. Node 5 is the last to hear the signal, at time 8, so the network is fully reached at 8. The answer is the maximum of the final times."}]},{"id":"wrong-order-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you settle nodes in the order you first reach them?","summary":"A shortcut version settles a node the moment it has a finite tentative time and relaxes its edges right away. On this network 1→2 (6), 1→3 (2), 3→2 (1), node 2 is reached first along the direct edge. Watch what settling it immediately does.","workspacePanel":"trace","pitfall":"The code below settles a node as soon as it is pulled in discovery order, rather than always taking the unvisited node with the smallest tentative time. It relaxes from whatever it settles.","whyItMatters":"Node 2 is reached directly at 6, but the cheaper route 1→3→2 delivers it at 3. Settling node 2 before the closer node 3 freezes the wrong time. The fix is to always settle the smallest tentative distance first, so node 3 at 2 settles before node 2.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"INF = 10 ** 9\ndist = [0, INF, INF]\ndone = [0, 0, 0]\nfor u in order:\n    done[u] = 1\n    for v, w in adj[u]:\n        if done[v] == 1:\n            continue\n        cand = dist[u] + w\n        if cand < dist[v]:\n            dist[v] = cand\nreturn dist[2]","typeContext":{"symbols":{"adj":{"kind":"list","item":{"kind":"list","item":{"kind":"list","item":"int"}}},"order":{"kind":"list","item":"int"}}},"steps":[{"id":"settle-source","title":"Settle the source and offer its edges","codeLine":10,"summary":"Node 1 is final at 0. It offers 1→2 = 6 and 1→3 = 2, so node 2 is tentatively 6 and node 3 is tentatively 2.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[1,2,6],[1,3,2],[3,2,1]],"current":1,"visited":[1],"highlighted":[2],"activeEdges":[[1,2]]},"arrays":[{"name":"dist","values":[0,6,2],"current":0}]}},{"id":"settle-node2-early","title":"It settles node 2 next because it was reached first","codeLine":5,"summary":"Following discovery order, node 2 is settled at 6 and frozen, even though node 3 sits at a smaller tentative 2 and has not been settled.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[1,2,6],[1,3,2],[3,2,1]],"current":2,"visited":[1,2],"highlighted":[3]},"arrays":[{"name":"dist","values":[0,6,2],"current":1}]}},{"id":"wrong-frozen","title":"Node 3 arrives too late, and node 2 is wrong","codeLine":7,"summary":"Now node 3 settles and offers 3→2 = 2 + 1 = 3, but node 2 is already settled, so the guard skips it and its 6 stands. It returns 6 when the real fastest time to node 2 is 3.","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[1,2,6],[1,3,2],[3,2,1]],"current":3,"visited":[1,2,3],"highlighted":[2],"activeEdges":[[3,2]]},"arrays":[{"name":"dist","values":[0,6,2],"current":2}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const INF = (10 ** 9);\nconst dist = [0, INF, INF];\nconst done = [0, 0, 0];\nfor (const u of order) {\n    done[u] = 1;\n    for (const [v, w] of adj[u]) {\n        if (done[v] === 1) {\n            continue;\n        }\n        const cand = dist[u] + w;\n        if (cand < dist[v]) {\n            dist[v] = cand;\n        }\n    }\n}\nreturn dist[2];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":16},"statementBundles":{"8":{"startLine":8,"endLine":9},"11":{"startLine":12,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const INF = (10 ** 9);\nconst dist = [0, INF, INF];\nconst done = [0, 0, 0];\nfor (const u of order) {\n    done[u] = 1;\n    for (const [v, w] of adj[u]) {\n        if (done[v] === 1) {\n            continue;\n        }\n        const cand = dist[u] + w;\n        if (cand < dist[v]) {\n            dist[v] = cand;\n        }\n    }\n}\nreturn dist[2];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":16},"statementBundles":{"8":{"startLine":8,"endLine":9},"11":{"startLine":12,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int INF = 1000000000;\nList<Integer> dist = new ArrayList<>(List.of(0, INF, INF));\nList<Integer> done = new ArrayList<>(List.of(0, 0, 0));\nfor (Integer u : order) {\n    done.set(u, 1);\n    for (List<Integer> item : adj.get(u)) {\n        int v = item.get(0);\n        int w = item.get(1);\n        if (done.get(v) == 1) {\n            continue;\n        }\n        int cand = dist.get(u) + w;\n        if (cand < dist.get(v)) {\n            dist.set(v, cand);\n        }\n    }\n}\nreturn dist.get(2);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":12,"10":13,"11":14,"12":18},"statementBundles":{"6":{"startLine":6,"endLine":8},"8":{"startLine":10,"endLine":11},"11":{"startLine":14,"endLine":17}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int INF = 1000000000;\nList<int> dist = new() { 0, INF, INF };\nList<int> done = new() { 0, 0, 0 };\nforeach (int u in order) {\n    done[u] = 1;\n    foreach (var item in adj[u]) {\n        int v = item[0];\n        int w = item[1];\n        if (done[v] == 1) {\n            continue;\n        }\n        int cand = dist[u] + w;\n        if (cand < dist[v]) {\n            dist[v] = cand;\n        }\n    }\n}\nreturn dist[2];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":12,"10":13,"11":14,"12":18},"statementBundles":{"6":{"startLine":6,"endLine":8},"8":{"startLine":10,"endLine":11},"11":{"startLine":14,"endLine":17}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int INF = 1000000000;\nvector<int> dist{0, INF, INF};\nvector<int> done{0, 0, 0};\nfor (int u : order) {\n    done[u] = 1;\n    for (vector<int> item : adj[u]) {\n        int v = item[0];\n        int w = item[1];\n        if (done[v] == 1) {\n            continue;\n        }\n        int cand = dist[u] + w;\n        if (cand < dist[v]) {\n            dist[v] = cand;\n        }\n    }\n}\nreturn dist[2];","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":12,"10":13,"11":14,"12":18},"statementBundles":{"6":{"startLine":6,"endLine":8},"8":{"startLine":10,"endLine":11},"11":{"startLine":14,"endLine":17}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Settling the closest node and relaxing its edges drained the sample network, every node ending with its fastest time.","Two networks deserve a look before you code: one where a node has no incoming route at all, and one where the whole network is a single node with nothing to send."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[1]},"arrays":[{"name":"dist","values":[0,2,5,6,8],"current":0}]}}]}},{"id":"unreachable-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if one node has no route from the source?","summary":"The network is 1→2 (4), 2→3 (5) with the broadcast starting at node 1, and node 4 has no incoming edge.","workspacePanel":"visualizer","options":[{"id":"minus-one","label":"-1, because node 4 never hears the signal","rationale":"Settling runs out of reachable nodes while node 4 is still ∞. A node left at ∞ can never be reached, so the network can never finish and the answer is -1.","isCorrect":true},{"id":"nine","label":"9, the time to reach the nodes that are reachable","rationale":"9 is the slowest reachable arrival, node 3. But node 4 never gets the signal at all, so the network is never fully reached and the answer is -1.","isCorrect":false},{"id":"skip","label":"Ignore node 4 and return the max over reachable nodes","rationale":"Every node must receive the signal for a finite answer. A single node stuck at ∞ forces -1; it cannot be skipped.","isCorrect":false}],"answer":"-1. Node 4 has no incoming edge, so it stays at ∞. Any node left at ∞ means the signal never reaches everyone, and the answer is -1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unreachable-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[1,2,4],[2,3,5]],"visited":[1,2,3],"current":3},"arrays":[{"name":"dist","values":[0,4,9,"∞"],"current":3}]}}]}},{"id":"single-node-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the network is a single node with no edges?","summary":"There is one node, the source itself, and the edge list is empty.","workspacePanel":"visualizer","options":[{"id":"zero","label":"0, the source already has the signal","rationale":"The source starts settled at time 0 and there is no other node to wait for, so the slowest arrival is the source’s own 0. The network is done immediately.","isCorrect":true},{"id":"minus-one","label":"-1, since there are no edges","rationale":"-1 means a node was left unreached. Here the only node is the source, which is already reached at 0, so nothing is missing.","isCorrect":false},{"id":"one","label":"1, for the single settling round","rationale":"Settling does not add time on its own. The source’s time is 0 and there is nothing farther, so the answer is 0.","isCorrect":false}],"answer":"0. The single node is the source, already settled at time 0, and there is nothing slower to wait for.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"graph":{"nodes":[{"id":1,"label":"1"}],"edges":[],"visited":[1],"current":1},"arrays":[{"name":"dist","values":[0],"current":0}]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Settle the closest unvisited node, relax its edges, and a leftover ∞ means -1.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Convert the 1-indexed labels to zero-based indices, set up a distance array with the source at 0 and everyone else at ∞, then repeatedly settle the unvisited node with the smallest tentative distance and relax its outgoing edges. When every node is settled, return the largest distance, or -1 if any node is still ∞."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[1,2,2],[1,3,7],[2,3,3],[2,4,8],[3,4,1],[4,5,2]],"current":1,"visited":[1]},"arrays":[{"name":"dist","values":[0,"∞","∞","∞","∞"],"current":0}]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the closest-first relaxation","eyebrow":"Code the rule","summary":"Now turn the settling into code: build zero-based weighted adjacency, seed the source distance, use a min-heap to settle the closest tentative node, then return the largest finite distance or -1 if a node is still unreached.","workspacePanel":"code","checkpoints":[{"id":"build-adjacency","title":"Build weighted adjacency","description":"Convert 1-indexed edges into a zero-based adjacency list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"builds_projected_result_sequence","scope":"convert-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Normalize the 1-indexed edge list into adjacency entries that can be used with zero-based distance indices.","doneWhen":"This step is done when every directed edge contributes a zero-based destination and weight under its zero-based source node.","shouldFailWhen":"This step should fail if the code indexes adjacency or distances with raw 1-indexed node labels.","roles":["weighted adjacency list","source label","zero-based endpoints"],"mustProve":["The implementation derives adjacency entries from `times`.","Both edge endpoints are shifted before they are used as array indices."],"mustNotAccept":["Subtracting one from only one endpoint.","Using raw input labels directly as adjacency or distance indices."],"equivalentVariants":["Append `(v - 1, w)` into `adj[u - 1]`.","First normalize edge triples, then populate adjacency from them."],"proofSnippets":[{"id":"py-network-delay-time-build-adjacency","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        source = k - 1\n        return len(adj) + source"}]},"commonMistakes":["Mixing 1-indexed input labels with zero-based arrays","Normalizing k but not the edge endpoints"],"hint":"Choose one indexing scheme before building adjacency or seeding the source."},{"id":"init-dist","title":"Initialize distances","description":"Create the distance array and seed only the source node to 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-dist","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize weighted shortest-path state so only the source starts reachable.","doneWhen":"This step is done when the code creates a length-n distance array filled with an infinity sentinel and writes 0 at the normalized source index before relaxation.","shouldFailWhen":"This step should fail if every node starts at 0 or if the source is not seeded before the heap loop.","roles":["distance array","infinity sentinel","source seed"],"mustProve":["The distance structure covers every node.","The source has distance 0 before closest-first relaxation starts.","Non-source nodes remain at the unreachable sentinel initially."],"mustNotAccept":["Initializing all nodes as reachable.","Seeding the source after the heap loop."],"equivalentVariants":["Use any large sentinel or infinity value.","Use any array-like distance container with one slot per node."],"proofSnippets":[{"id":"py-network-delay-time-init-dist","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n        return dist[source]"}]},"commonMistakes":["Starting all distances at 0","Forgetting to convert k before seeding the source"],"hint":"Everything starts unreachable except the source."},{"id":"closest-first-relaxation","title":"Relax from the closest node","description":"Use a min-heap to pop the closest tentative node and relax its outgoing edges.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"pushes_heap_values","scope":"heap-push"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"extracts_heap_values","scope":"heap-pop"}]}]},"semanticSpec":{"intent":"Drive weighted relaxation by the smallest tentative arrival time instead of scanning every edge in fixed rounds.","doneWhen":"This step is done when the code pushes tentative arrivals into a heap, pops the smallest one, skips stale entries, and pushes improved neighbor distances.","shouldFailWhen":"This step should fail if the code uses plain queue order, scans edges only once, or updates neighbors without a closest-first priority structure.","roles":["min-heap frontier","closest tentative node","stale-entry guard","distance update"],"mustProve":["Tentative arrivals are inserted into a priority heap.","The loop extracts the next closest tentative arrival from that heap.","Improved neighbor distances are returned to the heap for later settling."],"mustNotAccept":["Using a FIFO queue for weighted shortest paths.","Relaxing a neighbor without comparing against its current best distance."],"equivalentVariants":["Use stale-entry skipping with `time != dist[u]`.","Use an explicit settled set after the heap pop."],"proofSnippets":[{"id":"py-network-delay-time-closest-first-relaxation","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        import heapq\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n        heap = []\n        heapq.heappush(heap, (0, source))\n        while heap:\n            time, u = heapq.heappop(heap)\n            if time != dist[u]:\n                continue\n            for v, w in adj[u]:\n                cand = time + w\n                if cand < dist[v]:\n                    dist[v] = cand\n                    heapq.heappush(heap, (cand, v))"}]},"commonMistakes":["Using discovery order instead of distance order","Forgetting to push an improved neighbor back into the heap"],"hint":"The heap should hold `(arrival_time, node)` candidates."},{"id":"return-delay","title":"Return final delay","description":"Reject unreachable nodes and return the maximum finite shortest distance.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_scan_decision","scope":"return-result","readMode":"array-scan-value-query-v1"}]}]},"semanticSpec":{"intent":"Convert the settled distance state into the required network delay answer.","doneWhen":"This step is done when the code returns -1 if any node remains unreachable and otherwise returns the maximum distance in the final distance array.","shouldFailWhen":"This step should fail if max distance is returned while an infinite distance remains, or if the return is not based on the slowest final arrival.","roles":["final distance array","unreachable sentinel","maximum finite distance"],"mustProve":["The code checks for unreachable nodes after relaxation.","The valid return value is derived from the maximum final distance."],"mustNotAccept":["Returning the source distance.","Returning max(dist) without guarding unreachable nodes."],"equivalentVariants":["Compute `delay = max(dist)` and compare it with the sentinel.","Scan distances once, returning -1 on an unreachable entry and tracking the maximum finite distance."],"proofSnippets":[{"id":"py-network-delay-time-return-delay","language":"python","code":"class Solution:\n    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:\n        import heapq\n\n        adj = [[] for _ in range(n)]\n        for u, v, w in times:\n            adj[u - 1].append((v - 1, w))\n\n        INF = 10**18\n        dist = [INF] * n\n        source = k - 1\n        dist[source] = 0\n\n        heap = []\n        heapq.heappush(heap, (0, source))\n        while heap:\n            time, u = heapq.heappop(heap)\n            if time != dist[u]:\n                continue\n            for v, w in adj[u]:\n                cand = time + w\n                if cand < dist[v]:\n                    dist[v] = cand\n                    heapq.heappush(heap, (cand, v))\n\n        delay = max(dist)\n        if delay == INF:\n            return -1\n        return int(delay)\n"}]},"commonMistakes":["Returning the source distance instead of the farthest reachable distance","Treating an unreachable node as a very large answer"],"hint":"The signal finishes when the slowest reachable node receives it."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Settle the closest unvisited node first; once it is the closest, no later path can beat it.","workspacePanel":"code","body":["This is a shortest-path settling: keep a best-known time per node, and each round finalize the unvisited node with the smallest tentative time, then relax its outgoing edges.","The answer is the largest final time, since the network is done only when its slowest node hears the signal, or -1 if any node is left unreached."],"takeaways":[{"title":"Closest-first is what makes a settled time final","body":"Once the smallest tentative time is the closest unvisited node, every other route already costs more and edges only add time, so nothing can beat it."},{"title":"A leftover infinity means impossible, not slow","body":"A node still at the sentinel after every reachable node settles can never be reached, so the unreachable check returns -1."},{"title":"Each node settles once, relaxing its edges","body":"With at most n settles and a relax per edge, the work is about O((n + e) log n) with a heap, since every edge is offered only from a finalized source."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
