{"id":"detect-negative-cycle","title":"Detect Negative Cycle","difficulty":"medium","patterns":["bellman-ford"],"primaryConcept":"graph-shortest-path-negative","concepts":["graph-shortest-path-negative"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"weighted-graph-edges","primaryParam":"edges","sizeMetric":"nodes-plus-edges","secondaryParams":{"n":{"strategy":"scale-with-primary"}}},"description":"You are given `n` directed graph nodes labeled `0..n-1` and weighted directed edges where each edge is `[u, v, w]`.\n\nReturn `true` if the graph contains any negative-weight cycle, otherwise return `false`.\n\nA negative cycle may be in any connected component.","examples":[{"input":"n = 3, edges = [[0,1,1],[1,2,1],[2,0,-3]]","output":"true","explanation":"The cycle 0 -> 1 -> 2 -> 0 has total weight -1."},{"input":"n = 3, edges = [[0,1,2],[1,2,3]]","output":"false","explanation":"There is no cycle, so no negative cycle can exist."}],"constraints":[{"id":"1-n-200","text":"1 <= n <= 200","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":200}},{"id":"0-len-edges-2000","text":"0 <= len(edges) <= 2000","check":{"kind":"sizeRange","target":"edges","measure":"arrayLength","min":0,"max":2000}},{"id":"each-edge-is-u-v-w","text":"Each edge is [u, v, w]","check":{"kind":"shape","target":"edges","shape":"tupleArray","tupleLength":3}},{"id":"0-u-v-n","text":"0 <= u, v < n","check":[{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":0,"min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":1,"min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"10-6-w-10-6","text":"-10^6 <= w <= 10^6","check":{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":2,"min":-1000000,"max":1000000}}],"starterCode":"class Solution:\n    def hasNegativeCycle(self, n: int, edges: list[list[int]]) -> bool:\n        # Your code here\n        pass","functionName":"hasNegativeCycle","testCases":[{"id":"1","input":{"n":3,"edges":[[0,1,1],[1,2,1],[2,0,-3]]},"expected":true,"description":"Cycle has negative total weight."},{"id":"2","input":{"n":3,"edges":[[0,1,2],[1,2,3]]},"expected":false,"description":"A directed acyclic graph has no cycle."},{"id":"3","input":{"n":4,"edges":[[2,3,-2],[3,2,-2]]},"expected":true,"description":"Negative cycle in a disconnected component."},{"id":"4","input":{"n":1,"edges":[[0,0,-1]]},"expected":true,"description":"Negative self-loop."},{"id":"5","input":{"n":3,"edges":[[0,1,2],[1,2,-1],[2,0,-1]]},"expected":false,"description":"Cycle total is zero, not negative."},{"id":"h1","input":{"n":2,"edges":[[0,1,5],[1,0,-4]]},"expected":false,"description":"Positive total cycle."},{"id":"h2","input":{"n":5,"edges":[[0,1,4],[1,2,-6],[2,3,1],[3,1,1],[3,4,2]]},"expected":true,"description":"A multi-edge cycle keeps improving."},{"id":"h3","input":{"n":4,"edges":[]},"expected":false,"description":"No edges means no cycles."},{"id":"h4","input":{"n":4,"edges":[[0,1,-5],[1,2,2],[2,3,2]]},"expected":false,"description":"Negative edges without a cycle should not be reported."},{"id":"h5","input":{"n":2,"edges":[[0,0,0],[0,1,-1]]},"expected":false,"description":"A zero-weight self-loop is not a negative cycle."},{"id":"topup-1","input":{"n":4,"edges":[[0,1,1],[1,2,-2],[2,1,1],[2,3,2]]},"expected":true,"description":"Top-up case 1: a two-node directed cycle has total weight -1 even with an outgoing edge."},{"id":"topup-2","input":{"n":5,"edges":[[0,1,-2],[1,2,3],[2,0,1],[3,4,-5]]},"expected":false,"description":"Top-up case 2: negative paths and a zero-sum cycle should not be reported as negative cycles."}],"hints":[{"level":1,"content":"Bellman-Ford can detect a negative cycle if an edge can still relax on the nth pass."},{"level":2,"content":"Initialize all nodes to zero so every component is considered."},{"level":3,"content":"If any edge relaxes during pass `n`, return `true`; if a full pass makes no changes, return `false`."}],"guidedFlow":{"version":2,"progressRevision":"detect-negative-cycle-2026-07-19-cycle-removal-proof","approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"cycle-enumeration","name":"List every cycle and sum it","summary":"Walk out from each node, enumerate every directed cycle, and add up its edge weights to find one that totals below zero.","decisionReason":"The number of cycles can grow exponentially with the nodes, so on a 200-node graph this never finishes, even though any single cycle is cheap to sum.","complexity":{"time":"exponential","space":"O(n)"},"tradeoffs":["The cycle count explodes with graph size, so enumeration is hopeless past a handful of nodes."],"isOptimal":false},{"id":"bellman-ford-extra-pass","name":"Relax in passes, watch the nth","summary":"Relax every edge in n passes over a distance row. If any edge still lowers a distance on the nth pass, a negative cycle is pulling distances down forever.","decisionReason":"Without a negative cycle the distances settle within n minus one passes, so one improvement on pass n is exactly the cycle signal, found in O(n*m) without ever listing a cycle.","complexity":{"time":"O(n*m)","space":"O(n)"},"tradeoffs":["Scans all m edges across n passes, but the work is flat O(n*m) regardless of how many cycles exist."],"isOptimal":true}]},"codingCheckpoints":[{"id":"dist-init","title":"Initialize distances","description":"Create distance state that lets every component participate.","commonMistakes":["Only seeding node 0","Leaving all distances at infinity"],"hint":"Use zero for every node when detecting a cycle anywhere in the graph.","semanticSpec":{"intent":"Initialize weighted distance state before relaxation.","doneWhen":"The distance structure is created before the Bellman-Ford loop.","shouldFailWhen":"This step should fail if there is no distance state.","roles":["distance state","graph nodes"],"mustProve":["Weighted distance state is initialized."],"mustNotAccept":["Relaxing without distance state."],"equivalentVariants":["Use a super-source model or initialize every node to zero."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"all-component-dist-init","readMode":"graph-value-query-v1"}]}},{"id":"bellman-loop","title":"Repeat edge relaxation","description":"Run full edge scans and update distances when an edge improves.","commonMistakes":["Scanning edges only once","Using `<=` instead of strict improvement"],"hint":"The nth relaxation pass is what exposes negative cycles.","semanticSpec":{"intent":"Perform repeated weighted edge relaxation.","doneWhen":"The code repeats full edge scans and writes improved distance values.","shouldFailWhen":"This step should fail if edge relaxation is not repeated.","roles":["relaxation pass","edge list","distance state"],"mustProve":["Edges are repeatedly relaxed."],"mustNotAccept":["A single pass over edges."],"equivalentVariants":["Use exactly n passes or n - 1 passes plus one explicit final pass."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"bellman-loop","readMode":"graph-value-query-v1"}]}},{"id":"return-boolean","title":"Return the cycle verdict","description":"Return true when the extra pass still relaxes, otherwise false.","commonMistakes":["Returning true for any cycle","Forgetting the false fallback"],"hint":"Only an improvement on the final allowed pass proves a negative cycle.","semanticSpec":{"intent":"Return a boolean verdict from the weighted relaxation result.","doneWhen":"The function returns true for a final-pass relaxation and false when relaxation stabilizes.","shouldFailWhen":"This step should fail if the function never returns both verdicts.","roles":["final pass","boolean verdict"],"mustProve":["The weighted cycle boolean verdict is returned."],"mustNotAccept":["Returning a distance array or witness node."],"equivalentVariants":["Use an explicit extra scan or test inside the nth pass."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_weighted_cycle_boolean_verdict","scope":"return-boolean","readMode":"graph-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"Understand","eyebrow":"Read the problem","title":"Is any cycle worth less than nothing?","workspacePanel":"problem","body":["You get `n` nodes labeled `0..n-1` and a list of directed edges, each written `[u, v, w]`: a one-way arrow from `u` to `v` carrying weight `w`. Weights can be negative. Return `true` if some directed cycle has a total weight below zero, otherwise `false`.","A negative edge alone does not make a negative cycle. The directed edges must return to an earlier node with a total below zero."]},{"id":"enumerate-contrast","kind":"code-trace","source":"brute-force","chapter":"The obvious way","eyebrow":"Start naive","title":"Walk out from each node and total every loop","summary":"The literal reading of the task is to find the cycles and add them up: from each start node, walk edges, and whenever a walk returns to where it began, sum that loop's weights and check for a negative total. Watch how many walks the first node alone spawns.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def has_negative_cycle(n: int, edges: list[tuple[int, int, int]]) -> bool:\n    for start in range(n):\n        stack: list[tuple[int, int, int]] = [(start, 0, 1 << start)]\n        while stack:\n            node, total, seen = stack.pop()\n            for u, v, weight in edges:\n                if u != node:\n                    continue\n                if v == start and total + weight < 0:\n                    return True\n                if not (seen & (1 << v)):\n                    stack.append((v, total + weight, seen | (1 << v)))\n    return False","steps":[{"id":"start-0","title":"Begin every walk from node 0","codeLine":12,"summary":"Pick node 0 as a start and follow its only outgoing edge, 0->1, pushing node 1 with a running total of 1.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]}}},{"id":"extend-1","title":"Extend the walk to node 2","codeLine":12,"summary":"Pop node 1 off the stack. Its only edge is 1->2, so the walk pushes node 2 with the total now 1 + 1 = 2.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":1,"highlighted":[2],"activeEdges":[[1,2]]}}},{"id":"close-loop","title":"The edge 2->0 closes back on the start","codeLine":9,"summary":"Pop node 2. Its edge 2->0 returns to the start, so the loop total 1 + 1 - 3 = -1 is checked against zero. It is below zero, so this start reports a negative cycle.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"for (let start = 0; start < n; start++) {\n    const stack = [[start, 0, (1 << start)]];\n    while (stack.length > 0) {\n        const [node, total, seen] = stack.pop();\n        for (const [u, v, weight] of edges) {\n            if (u !== node) {\n                continue;\n            }\n            if (v === start && (total + weight) < 0) {\n                return true;\n            }\n            if (!((seen & (1 << v)))) {\n                stack.push([v, (total + weight), (seen | (1 << v))]);\n            }\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":18},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"12":{"startLine":13,"endLine":17}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"for (let start = 0; start < n; start++) {\n    const stack: Array<[number, number, number]> = [[start, 0, (1 << start)]];\n    while (stack.length > 0) {\n        const [node, total, seen] = stack.pop()!;\n        for (const [u, v, weight] of edges) {\n            if (u !== node) {\n                continue;\n            }\n            if (v === start && (total + weight) < 0) {\n                return true;\n            }\n            if (!((seen & (1 << v)))) {\n                stack.push([v, (total + weight), (seen | (1 << v))]);\n            }\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":13,"13":18},"statementBundles":{"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"12":{"startLine":13,"endLine":17}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"for (int start = 0; start < n; start++) {\n    List<(int, int, int)> stack = new() { (start, 0, 1 << start) };\n    while (stack.Count > 0) {\n        var (node, total, seen) = stack[stack.Count - 1];\n        stack.RemoveAt(stack.Count - 1);\n        foreach (var (u, v, weight) in edges) {\n            if (u != node) {\n                continue;\n            }\n            if (v == start && total + weight < 0) {\n                return true;\n            }\n            if ((seen & 1 << v) == 0) {\n                stack.Add((v, total + weight, seen | 1 << v));\n            }\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":19},"statementBundles":{"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"for (int start = 0; start < n; start++) {\n    vector<tuple<int, int, int>> stack_{{start, 0, (1 << start)}};\n    while (!stack_.empty()) {\n        auto popped_item = stack_.back(); stack_.pop_back();\n        auto [node, total, seen] = popped_item;\n        for (auto [u, v, weight] : edges) {\n            if (u != node) {\n                continue;\n            }\n            if ((v == start && (total + weight) < 0)) {\n                return true;\n            }\n            if (!(seen & (1 << v))) {\n                stack_.push_back(tuple<int, int, int>{v, (total + weight), (seen | (1 << v))});\n            }\n        }\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":14,"13":19},"statementBundles":{"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":18}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"for (int start = 0; start < n; start++) {\n    List<List<Integer>> stack = new ArrayList<>(Arrays.asList(new ArrayList<>(List.of(start, 0, (1 << start)))));\n    while (!stack.isEmpty()) {\n        List<Integer> item = stack.remove(stack.size() - 1);\n        int node = item.get(0);\n        int total = item.get(1);\n        int seen = item.get(2);\n        for (List<Integer> edge : edges) {\n            int u = edge.get(0);\n            int v = edge.get(1);\n            int weight = edge.get(2);\n            if (u != node) {\n                continue;\n            }\n            if ((v == start && (total + weight) < 0)) {\n                return true;\n            }\n            if ((seen & (1 << v)) == 0) {\n                stack.add(new ArrayList<>(List.of(v, (total + weight), (seen | (1 << v)))));\n            }\n        }\n    }\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":8,"7":12,"8":13,"9":15,"10":16,"11":18,"12":19},"statementBundles":{"5":{"startLine":4,"endLine":7},"6":{"startLine":8,"endLine":11},"8":{"startLine":13,"endLine":14},"10":{"startLine":16,"endLine":17},"12":{"startLine":19,"endLine":23}}}}}},{"id":"enumerate-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Count the walks","title":"How many walks does enumeration spawn on a dense graph?","summary":"Each start node fans out along every outgoing edge, and each of those extends along every edge from the next node, and so on. The graph below is denser than the 3-node example: node 0 alone forks three ways, and every node it reaches forks again.","workspacePanel":"visualizer","options":[{"id":"exponential","label":"Roughly the number of paths through the graph, which grows exponentially with the nodes","rationale":"Every node can branch to many others, and each branch branches again, so the distinct walks multiply at each step. On a graph where nodes point at most others, the path count explodes; a 200-node graph has more cycles than you could ever total one by one.","isCorrect":true},{"id":"linear","label":"One walk per node, so about n walks","rationale":"A single walk per start would be true only if each node had one outgoing edge. With several edges out of a node, every walk forks into many, and the total grows far past n.","isCorrect":false},{"id":"edge-count","label":"One walk per edge, so about m walks","rationale":"Walks are not edges; a walk is a chain of edges, and the chains compound. The work is the number of distinct paths, which dwarfs the edge count on anything but a sparse line.","isCorrect":false}],"answer":"The walks multiply at every branch, so their count grows exponentially with the nodes. Summing each loop is cheap, but there are far too many loops to list inside the 200-node limit. Enumeration cannot scale; the work has to be flat in the graph size, not in the number of cycles.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"enumerate-cost-step","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,1],[0,2,1],[0,3,1],[1,2,1],[1,4,1],[2,3,1],[2,4,1],[3,4,1],[3,1,1],[4,0,1]],"current":0,"highlighted":[1,2,3],"activeEdges":[[0,1],[0,2],[0,3]]}}}]}},{"id":"path-dominance","kind":"case-probe","chapter":"The trick","eyebrow":"Compare two arrivals","title":"Two paths reach node 3. Which history can never help again?","summary":"One path reaches node 3 with total weight 4. Another reaches the same node with total weight -1. From node 3 onward, both paths have exactly the same outgoing choices.","workspacePanel":"visualizer","options":[{"id":"discard-four","label":"Discard the path totaling 4; every shared continuation stays 5 heavier","rationale":"Both histories now stand at node 3 and will add the same suffix weights. Starting from -1 instead of 4 remains better by 5 after every possible continuation, so the total 4 can never lead to a cheaper result.","isCorrect":true},{"id":"keep-both","label":"Keep both paths because they used different earlier nodes","rationale":"Their earlier nodes no longer affect which edges are available. Once both paths reach node 3, only the accumulated total differs, and the larger total is dominated forever.","isCorrect":false},{"id":"discard-negative","label":"Discard the path totaling -1 because negative totals are unsafe","rationale":"A lower total is exactly what a cheapest-path state wants to preserve. Negative weight does not invalidate the path; it makes this arrival strictly more useful than the arrival totaling 4.","isCorrect":false}],"answer":"Discard the arrival totaling 4. At the same node, every future suffix is shared, so adding that suffix to -1 always beats adding it to 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-arrivals-at-three","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,2],[1,3,2],[0,2,-3],[2,3,2],[3,4,5]],"current":3,"highlighted":[3],"activeEdges":[[1,3],[2,3]]},"arrays":[{"name":"arrival total at node 3","values":[4,-1],"current":1}]}}]}},{"id":"compact-state","kind":"case-probe","chapter":"The trick","eyebrow":"Find the state","title":"What compact state could replace enumerating every loop?","summary":"Enumeration drowns because it tracks whole walks. To stay flat in the graph size, the algorithm has to remember far less than every path. What single piece of per-node bookkeeping carries enough to expose a negative loop?","workspacePanel":"visualizer","options":[{"id":"cheapest-total","label":"The cheapest known total weight to reach each node","rationale":"One number per node, the best total found so far to reach it, is enough. An edge `u->v` can lower that number for `v`, and a loop whose weights net below zero keeps lowering its own nodes forever. The state is O(n), independent of how many walks exist.","isCorrect":true},{"id":"visited-set","label":"The set of nodes each walk has already visited","rationale":"Tracking visited nodes per walk is exactly the enumeration that just blew up: there is one such set per walk, and the walks multiply exponentially. That is the state we are trying to escape.","isCorrect":false},{"id":"all-cycle-sums","label":"The running total of every distinct cycle","rationale":"Storing a sum per cycle is no cheaper than listing the cycles, and there are exponentially many. The whole point is to avoid anything that scales with the cycle count.","isCorrect":false}],"answer":"Keep one number per node: the cheapest total weight found so far to reach it. That is O(n) state, not one entry per walk or per cycle, so it stays flat in the graph size while still letting a negative loop pull its own numbers down.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"compact-state-step","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]]},"arrays":[{"name":"dist","values":[0,0,0]}]}}]}},{"id":"reframe","kind":"info","chapter":"The trick","eyebrow":"Change the question","title":"Sweep the edges to lower those distances","workspacePanel":"visualizer","body":["Call that per-node number `dist[v]`: the cheapest total weight found so far to reach `v`. With the cycles gone, the only thing left to do is improve those numbers.","Sweep the whole edge list and, for any edge `u->v` of weight `w`, lower `dist[v]` to `dist[u] + w` whenever that is cheaper. The picture below catches one such relaxation mid-sweep: edge 2->0 offers 0 + (-3) = -3, below dist[0] = 0, so dist[0] drops to -3. One sweep lets every edge push its weight forward once like this."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reframe-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":2,"highlighted":[0],"activeEdges":[[2,0]]},"arrays":[{"name":"dist","values":[-3,0,0],"current":0}]}}]}},{"id":"sweep-path-bound","kind":"case-probe","chapter":"The trick","eyebrow":"Bound an honest path","title":"How many edges can a simple path use before it must repeat a node?","summary":"A graph has n nodes. A simple path visits each node at most once, and each full edge sweep guarantees that paths one edge longer have had room to contribute to the distance state.","workspacePanel":"visualizer","options":[{"id":"n-minus-one","label":"n - 1 edges; the same number of sweeps covers every non-repeating route","rationale":"Visiting n distinct nodes connects them with at most n - 1 edges. After n - 1 full sweeps, every simple path has had enough passes to contribute its total. In-place updates may travel farther within a sweep, but they never weaken this guarantee.","isCorrect":true},{"id":"n-edges","label":"At most n edges, because a path may return to its first node once","rationale":"Returning to the first node repeats it and creates a cycle. A simple path stops before any repeated node, so its maximum is n - 1 edges.","isCorrect":false},{"id":"edge-count","label":"As many edges as the graph contains","rationale":"The graph may contain many branching edges, but one simple path cannot visit more than n distinct nodes. The node count bounds its length; the graph's total edge count does not.","isCorrect":false}],"answer":"A simple path uses at most n - 1 edges. Therefore n - 1 full sweeps guarantee that every path without a repeated node has contributed. Any later improvement cannot be explained by discovering a longer simple path; the next question is what that observation proves.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"longest-simple-path","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[1,2,-1],[2,3,4]],"current":3,"highlighted":[0,1,2,3],"activeEdges":[[0,1],[1,2],[2,3]]},"values":{"nodes":4,"simplePathEdges":3,"guaranteedSweeps":3}}}]}},{"id":"cycle-removal-bound","kind":"case-probe","chapter":"The trick","eyebrow":"Remove a harmless repeat","title":"A walk repeats node 1. If the loop segment is not negative, should a cheapest route keep it?","summary":"The walk 0->1->2->1->3 repeats node 1. The loop 1->2->1 totals 3. Removing that loop leaves 0->1->3 with the same start and destination.","workspacePanel":"visualizer","options":[{"id":"remove-loop","label":"Remove the loop; the route reaches node 3 with a total lower by 3","rationale":"The repeated segment returns to node 1 and adds 3 before the route continues along the same edge to node 3. Deleting it preserves the destination and makes the total cheaper. A zero-total loop could also be removed without making the route worse.","isCorrect":true},{"id":"keep-loop","label":"Keep the loop because visiting more edges may reveal a cheaper route later","rationale":"After returning to node 1, the available continuation is exactly the one node 1 already had. A nonnegative loop adds cost without unlocking a new suffix, so it cannot improve the route.","isCorrect":false},{"id":"discard-route","label":"Discard the entire route because any repeated node makes it invalid","rationale":"The route is still useful after removing only the repeated loop. What matters is that a cheapest representative can be chosen without the nonnegative cycle.","isCorrect":false}],"answer":"Remove the loop. If no cycle has negative total, every repeated cycle can be deleted without increasing the route's weight. A cheapest route can therefore be represented by a simple path, which uses at most n - 1 edges.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"remove-positive-loop","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[1,2,1],[2,1,2],[1,3,4]],"current":1,"highlighted":[1,2],"activeEdges":[[1,2],[2,1]]},"values":{"walkTotal":9,"loopTotal":3,"withoutLoop":6}}}]}},{"id":"discover-signal","kind":"choice","source":"pattern-recognition","chapter":"The trick","eyebrow":"Find the signal","title":"What would prove a negative cycle without naming it?","workspacePanel":"visualizer","summary":"Every simple path has already had enough sweeps to contribute. The panel shows a distance falling once more on the next full sweep.","quiz":{"contract":"pattern-recognition-v1","question":"What would prove a negative cycle without naming it?","signalPrompt":"Which observation separates the run that settled from the run that did not?","options":[{"id":"extra-pass","label":"A sweep that still lowers some distance after enough sweeps to settle a cycle-free graph","signal":"Without a negative cycle, shortest paths use at most n minus one edges, so n minus one sweeps settle every distance and the next sweep changes nothing. If a sweep keeps lowering a distance past that point, a cycle is feeding the distances down with no floor.","rationale":"A cycle-free graph stops improving within n minus one sweeps. An improvement on the nth sweep can only come from a loop whose weights total below zero, pulling the distance lower every lap.","isCorrect":true},{"id":"any-negative","label":"Any sweep that lowers a distance at all","signal":"Distances drop on a perfectly normal graph too.","rationale":"Lowering a distance is just a shorter path being found; it happens on graphs with no cycle at all. The signal is improvement that refuses to stop, not improvement itself.","isCorrect":false},{"id":"negative-edge","label":"The presence of any negative-weight edge","signal":"A negative edge can sit on a path that never loops.","rationale":"A single negative edge on a straight path lowers a distance once and settles. Only a loop whose total is negative keeps paying out, so a lone negative edge proves nothing.","isCorrect":false},{"id":"revisit-node","label":"A walk that returns to a node it already visited","signal":"That is the enumeration idea again.","rationale":"Revisiting a node detects a cycle, but not whether its total is negative, and finding such walks is the exponential search just rejected. The distance method never tracks walks at all.","isCorrect":false}],"missFeedback":"A cycle-free graph settles within n minus one sweeps; look for improvement that outlasts that.","hint":"If distances still fall after every shortest path has had room to form, something is feeding them down forever."},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"signal-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[-4,-2,-1],"current":1}]}}]}},{"id":"seed-all","kind":"case-probe","chapter":"The trick","eyebrow":"Seed the distances","title":"What should every starting distance be?","summary":"The graph may have several disconnected components.","workspacePanel":"visualizer","options":[{"id":"all-zero","label":"Zero for every node","rationale":"Seeding every `dist` at 0 puts a launch pad in every component at once, so a negative cycle anywhere can start pulling its own distances down. No node is privileged, which is exactly what a query about any cycle anywhere needs.","isCorrect":true},{"id":"one-source","label":"Zero at node 0 and infinity everywhere else","rationale":"Single-source seeding only explores cycles reachable from node 0. A negative cycle living in a separate component never gets a finite distance to lower, so it is missed entirely. The task asks about every component.","isCorrect":false},{"id":"all-inf","label":"Infinity for every node","rationale":"If every distance starts at infinity, no edge can ever fire, because `inf + w` is not below `inf`. Nothing relaxes and no cycle is found. Some node has to start finite, and seeding all of them at zero starts all of them.","isCorrect":false}],"answer":"Seed every node at zero. That plants a starting point in every component, so a negative cycle in any part of the graph can begin lowering its own distances on the first sweep. A single zero-source seed would miss any cycle node 0 cannot reach.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[2,3,-2],[3,2,-2]]},"arrays":[{"name":"dist","values":[0,0,0,0]}]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it run","title":"Seed all zero, then sweep three times","workspacePanel":"visualizer","body":["Run it on the loop 0->1 (1), 1->2 (1), 2->0 (-3) with n = 3. Every distance starts at 0, and each sweep relaxes all three edges in the order they are listed.","Because n = 3, sweeps numbered 0 and 1 are the n minus one that settle an honest graph. Sweep 2 is the nth: any improvement there is the signal. Predict each sweep before it runs."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]]},"arrays":[{"name":"dist","values":[0,0,0]}]}}]}},{"id":"trace","kind":"dry-run","chapter":"Trace","eyebrow":"Predict each sweep","title":"Trace the repeated relaxation","workspacePanel":"visualizer","beats":[{"id":"sweep-0","title":"Sweep 0: which edge is the only one that lowers a distance?","summary":"All distances are 0. Each edge tries `dist[u] + w < dist[v]`.","prompt":"Edges fire in order: 0->1 (1), 1->2 (1), 2->0 (-3).","options":[{"id":"edge-20","label":"Only 2->0, which sets dist[0] to -3","rationale":"0->1 offers 0 + 1 = 1, not below dist[1] = 0, so it does not fire. 1->2 offers 0 + 1 = 1, not below dist[2] = 0, so it does not fire. 2->0 offers 0 - 3 = -3, below dist[0] = 0, so dist[0] drops to -3.","isCorrect":true},{"id":"edge-01","label":"Only 0->1, which sets dist[1] to 1","rationale":"0->1 would raise dist[1] from 0 to 1, and relaxation only lowers, never raises. Positive edges out of a zero-seeded node never fire on the first sweep.","isCorrect":false},{"id":"all-three","label":"All three edges fire","rationale":"Two of the three offer a value not below the current distance, so they do nothing. Only the negative edge 2->0 improves anything this sweep.","isCorrect":false}],"answer":"Only 2->0 fires, dropping dist[0] to -3. The two positive edges offer values not below 0, so they leave their targets alone."},{"id":"sweep-1","title":"Sweep 1: now what does 0->1 do?","summary":"dist is [-3, 0, 0] going into the second sweep.","prompt":"0->1 reads the dist[0] that the last sweep lowered to -3.","options":[{"id":"cascade","label":"0->1 sets dist[1] to -2, then the others cascade lower","rationale":"dist[0] is now -3, so 0->1 offers -3 + 1 = -2, below dist[1] = 0. Then 1->2 offers -2 + 1 = -1, below 0, and 2->0 offers -1 - 3 = -4, below -3. Every edge fires; distances keep falling.","isCorrect":true},{"id":"nothing","label":"Nothing fires; the distances are settled","rationale":"dist[0] just became -3, which feeds 0->1 a value below dist[1]. Far from settling, this sweep lowers all three distances.","isCorrect":false},{"id":"only-01","label":"Only 0->1 fires and the rest stay put","rationale":"Once 0->1 lowers dist[1], the next edge 1->2 reads that new value and fires too, and 2->0 follows. The improvement chains down the whole loop in one sweep.","isCorrect":false}],"answer":"0->1 sees dist[0] = -3 and sets dist[1] = -2, then 1->2 sets dist[2] = -1, then 2->0 sets dist[0] = -4. The whole loop drops; nothing has settled."},{"id":"sweep-2","title":"Sweep 2 is the nth: does any edge still lower a distance?","summary":"dist is [-4, -2, -1]. This is the last of n sweeps for n = 3.","prompt":"This is the third sweep for n = 3. Does 0->1 still improve dist[1]?","options":[{"id":"still-improves","label":"Yes, 0->1 lowers dist[1] again, so the answer is true","rationale":"dist[0] = -4, so 0->1 offers -4 + 1 = -3, below dist[1] = -2. An improvement on the nth sweep is the proof: the loop is still paying out, its total is negative, and there is no floor. Return true.","isCorrect":true},{"id":"settled","label":"No, the distances have stopped moving","rationale":"The previous sweep already lowered dist[0] to -4, and -4 + 1 = -3 is still below dist[1] = -2. The improvements never stop, which is exactly the signal.","isCorrect":false},{"id":"need-more","label":"It improves, but that alone proves nothing","rationale":"Improvement specifically on sweep n is the proof. A cycle-free graph settles within n minus one sweeps, so any lowering on the nth sweep can only come from a negative cycle.","isCorrect":false}],"answer":"Yes. On the nth sweep 0->1 still lowers dist[1] from -2 to -3. A settled graph would change nothing here, so this improvement proves a negative-total loop. Return true."}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-0","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[0,0,0],"current":1}]}},{"id":"sweep-1","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[-3,0,0],"current":1}]}},{"id":"sweep-2","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[-4,-2,-1],"current":1}]}}]}},{"id":"pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Could a relaxation on `<=` work the same?","summary":"Writing the relaxation as `dist[u] + w <= dist[v]` looks harmless, since an equal value is no worse than what is there, and it still passes the negative-cycle examples. Watch it judge a cycle that nets exactly zero.","pitfall":"The code below relaxes on `dist[u] + w <= dist[v]`, so an edge that offers a value equal to the current distance still rewrites it and flags an update.","workspacePanel":"trace","whyItMatters":"A cycle whose weights total zero never lowers a distance, but `<=` flags it as updated on every lap because the same value rewrites equal to itself. The loop never reports settled, so the nth sweep always sees an update and falsely returns true. The fix is strict `<`: relax only when the new distance is genuinely smaller, so a zero-sum loop stops on its own.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def has_negative_cycle(n: int, edges: list[tuple[int, int, int]]) -> bool:\n    dist: list[int] = [0] * n\n    for i in range(n):\n        updated = False\n        for u, v, weight in edges:\n            if dist[u] + weight <= dist[v]:\n                dist[v] = dist[u] + weight\n                updated = True\n                if i == n - 1:\n                    return True\n        if not updated:\n            return False\n    return False","steps":[{"id":"zero-sweep-0","title":"A zero-sum loop on edges 0->1 (2), 1->2 (-1), 2->0 (-1)","codeLine":6,"summary":"This loop totals 2 - 1 - 1 = 0, so the answer should be false. Seeded at [0, 0, 0], sweep 0 leaves 0->1 alone (0 + 2 = 2 is above dist[1] = 0), fires 1->2 to set dist[2] = -1, then fires 2->0 to set dist[0] = -2. The sweep ends at [-2, 0, -1] with updated = true.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,2],[1,2,-1],[2,0,-1]],"current":2,"highlighted":[0],"activeEdges":[[2,0]]},"arrays":[{"name":"dist","values":[-2,0,-1],"current":0},{"name":"updated","values":[1]}]}},{"id":"zero-equal-rewrite","title":"A later sweep rewrites dist[1] to its own value","codeLine":6,"summary":"On the next sweep dist[0] = -2, so 0->1 offers -2 + 2 = 0, exactly equal to dist[1] = 0. Under `<=` that equality passes: dist[1] is rewritten to 0. The array stays the same, and `updated` is set to true. The same equal-value rewrite then happens on 1->2 and 2->0, so the sweep ends at [-2, 0, -1] again with updated = true.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,2],[1,2,-1],[2,0,-1]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[-2,0,-1],"current":1},{"name":"updated","values":[1]}]}},{"id":"zero-never-settles","title":"`updated` stays true, so the loop never reports settled","codeLine":11,"summary":"Because some edge rewrites an equal value on every sweep, `updated` is never false, so the early `return False` never fires even though the distances stopped changing after sweep 0. The sweeps run all the way to the nth.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,2],[1,2,-1],[2,0,-1]]},"arrays":[{"name":"dist","values":[-2,0,-1]},{"name":"updated","values":[1]}]}},{"id":"zero-false-positive","title":"Sweep n rewrites an equal value and returns true","codeLine":10,"summary":"On the nth sweep (`i == n - 1`) the same equal-value rewrite passes the `<=` test, so the `i == n - 1` branch fires and the function returns true for a loop that nets exactly zero. The verdict is wrong: the distances never actually improved past sweep 0.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,2],[1,2,-1],[2,0,-1]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[-2,0,-1],"current":1},{"name":"updated","values":[1]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dist = Array(n).fill(0);\nfor (let i = 0; i < n; i++) {\n    let updated = false;\n    for (const [u, v, weight] of edges) {\n        if ((dist[u] + weight) <= dist[v]) {\n            dist[v] = (dist[u] + weight);\n            updated = true;\n            if (i === (n - 1)) {\n                return true;\n            }\n        }\n    }\n    if (!updated) {\n        return false;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13,"12":14,"13":17},"statementBundles":{"10":{"startLine":9,"endLine":12},"12":{"startLine":14,"endLine":16}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dist = Array(n).fill(0);\nfor (let i = 0; i < n; i++) {\n    let updated = false;\n    for (const [u, v, weight] of edges) {\n        if ((dist[u] + weight) <= dist[v]) {\n            dist[v] = (dist[u] + weight);\n            updated = true;\n            if (i === (n - 1)) {\n                return true;\n            }\n        }\n    }\n    if (!updated) {\n        return false;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13,"12":14,"13":17},"statementBundles":{"10":{"startLine":9,"endLine":12},"12":{"startLine":14,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dist = Enumerable.Repeat<int>(0, n).ToList();\nfor (int i = 0; i < n; i++) {\n    bool updated = false;\n    foreach (var (u, v, weight) in edges) {\n        if (dist[u] + weight <= dist[v]) {\n            dist[v] = dist[u] + weight;\n            updated = true;\n            if (i == n - 1) {\n                return true;\n            }\n        }\n    }\n    if (!updated) {\n        return false;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13,"12":14,"13":17},"statementBundles":{"10":{"startLine":9,"endLine":12},"12":{"startLine":14,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dist = vector<int>(n, 0);\nfor (int i = 0; i < n; i++) {\n    bool updated = false;\n    for (auto [u, v, weight] : edges) {\n        if ((dist[u] + weight) <= dist[v]) {\n            dist[v] = (dist[u] + weight);\n            updated = true;\n            if (i == (n - 1)) {\n                return true;\n            }\n        }\n    }\n    if (!updated) {\n        return false;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":13,"12":14,"13":17},"statementBundles":{"10":{"startLine":9,"endLine":12},"12":{"startLine":14,"endLine":16}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] dist = new int[n];\nfor (int i = 0; i < n; i++) {\n    boolean updated = false;\n    for (List<Integer> edge : edges) {\n        int u = edge.get(0);\n        int v = edge.get(1);\n        int weight = edge.get(2);\n        if ((dist[u] + weight) <= dist[v]) {\n            dist[v] = (dist[u] + weight);\n            updated = true;\n            if (i == (n - 1)) {\n                return true;\n            }\n        }\n    }\n    if (!updated) {\n        return false;\n    }\n}","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":8,"7":9,"8":10,"9":11,"10":12,"11":16,"12":17},"statementBundles":{"5":{"startLine":4,"endLine":7},"10":{"startLine":12,"endLine":15},"12":{"startLine":17,"endLine":19}}}}}},{"id":"edge-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which graphs could fool the sweep?","workspacePanel":"visualizer","body":["Strict `<` relaxation with an all-zero seed handles the loop you traced. Before coding, push on the shapes most likely to slip through: a graph where no edge ever fires, and a cycle whose negative loop hides where node 0 cannot reach it.","Each one targets a different part of the rule, the seed or the strict comparison. Decide what the sweep reports for each."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[2,3,-2],[3,2,-2]]},"arrays":[{"name":"dist","values":[0,0,0,0]}]}}]}},{"id":"edge-no-edges","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With no edges at all, what does the first sweep report?","summary":"n = 4 and the edge list is empty, so the loop body never relaxes anything.","workspacePanel":"visualizer","options":[{"id":"settles-false","label":"The first sweep makes no update, so it returns false right away","rationale":"With no edges, the inner loop never sets `updated`, so the `if not updated: return False` fires on the very first sweep. No edges means no cycle, and the answer falls out with no special case.","isCorrect":true},{"id":"needs-guard","label":"It needs an explicit empty-edge check first","rationale":"No guard is needed. An empty edge list simply produces a sweep with no updates, which the settle check already turns into false. Adding a special case would be dead code.","isCorrect":false},{"id":"crashes","label":"It loops n times over nothing and could misreport true","rationale":"It cannot reach the nth-sweep return, because the settle check exits on sweep 0. The `return True` only fires on an update during sweep n, and there are no updates at all.","isCorrect":false}],"answer":"It returns false on the first sweep. With no edges nothing relaxes, `updated` stays false, and the settle check exits immediately. The empty graph needs no special handling.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-edges-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[]},"arrays":[{"name":"dist","values":[0,0,0,0]}]}}]}},{"id":"edge-disconnected","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"A negative loop sits at nodes 2 and 3, far from node 0. Found?","summary":"n = 4 with edges 2->3 (-2) and 3->2 (-2). Nodes 0 and 1 have no edges at all.","workspacePanel":"visualizer","options":[{"id":"found","label":"Yes, because every node was seeded at zero","rationale":"dist[2] and dist[3] both start at 0, so 2->3 and 3->2 fire from the first sweep and keep lowering each other lap after lap. The all-zero seed gave the isolated component its own launch pad, so its negative loop surfaces even though node 0 cannot reach it.","isCorrect":true},{"id":"missed","label":"No, the search starts at node 0 and never reaches them","rationale":"There is no single start node here. Seeding every distance at zero means the relaxation runs everywhere at once, so a component disconnected from node 0 is still swept.","isCorrect":false},{"id":"depends","label":"Only if the edges happen to be listed before node 0's edges","rationale":"Edge order within a sweep does not matter for detection across n sweeps; what matters is that nodes 2 and 3 start finite. The zero seed guarantees that, independent of listing order.","isCorrect":false}],"answer":"Yes. Both nodes started at zero, so 2->3 and 3->2 relax from the first sweep and keep improving across all n sweeps, tripping the nth-sweep return. Seeding every node at zero makes a disconnected negative cycle visible.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"disconnected-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[2,3,-2],[3,2,-2]],"current":2,"highlighted":[3],"activeEdges":[[2,3]]},"arrays":[{"name":"dist","values":[0,0,0,0]}]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the sweep into code","summary":"All distances seeded at zero, strict `<`, and the nth-sweep improvement as the verdict.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Three moves. Start a distance for every node at zero so each component can participate. Sweep the edge list up to n times, lowering a node's distance only when an edge offers a strictly smaller value, and bail early on any sweep that changes nothing. If an edge still improves on the nth sweep, return true; otherwise return false.","The picture shows the all-zero seed the first step creates. The one thing the sweep hinges on is strict improvement: relax only when the new distance is genuinely smaller, never on a tie."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[1,2,1],[2,0,-3]]},"arrays":[{"name":"dist","values":[0,0,0]}]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the sweep","title":"Build the repeated relaxation","summary":"Now turn the sweep into code: seed every node's distance at zero, sweep the edges up to n times lowering a distance only on a strictly smaller value, then return true if an edge still improves on the nth sweep and false once a sweep settles.","workspacePanel":"code","checkpoints":[{"id":"dist-init","title":"Initialize distances","description":"Create distance state that lets every component participate.","commonMistakes":["Only seeding node 0","Leaving all distances at infinity"],"hint":"Use zero for every node when detecting a cycle anywhere in the graph.","semanticSpec":{"intent":"Initialize weighted distance state before relaxation.","doneWhen":"The distance structure is created before the Bellman-Ford loop.","shouldFailWhen":"This step should fail if there is no distance state.","roles":["distance state","graph nodes"],"mustProve":["Weighted distance state is initialized."],"mustNotAccept":["Relaxing without distance state."],"equivalentVariants":["Use a super-source model or initialize every node to zero."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"all-component-dist-init","readMode":"graph-value-query-v1"}]}},{"id":"bellman-loop","title":"Repeat edge relaxation","description":"Run full edge scans and update distances when an edge improves.","commonMistakes":["Scanning edges only once","Using `<=` instead of strict improvement"],"hint":"The nth relaxation pass is what exposes negative cycles.","semanticSpec":{"intent":"Perform repeated weighted edge relaxation.","doneWhen":"The code repeats full edge scans and writes improved distance values.","shouldFailWhen":"This step should fail if edge relaxation is not repeated.","roles":["relaxation pass","edge list","distance state"],"mustProve":["Edges are repeatedly relaxed."],"mustNotAccept":["A single pass over edges."],"equivalentVariants":["Use exactly n passes or n - 1 passes plus one explicit final pass."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"bellman-loop","readMode":"graph-value-query-v1"}]}},{"id":"return-boolean","title":"Return the cycle verdict","description":"Return true when the extra pass still relaxes, otherwise false.","commonMistakes":["Returning true for any cycle","Forgetting the false fallback"],"hint":"Only an improvement on the final allowed pass proves a negative cycle.","semanticSpec":{"intent":"Return a boolean verdict from the weighted relaxation result.","doneWhen":"The function returns true for a final-pass relaxation and false when relaxation stabilizes.","shouldFailWhen":"This step should fail if the function never returns both verdicts.","roles":["final pass","boolean verdict"],"mustProve":["The weighted cycle boolean verdict is returned."],"mustNotAccept":["Returning a distance array or witness node."],"equivalentVariants":["Use an explicit extra scan or test inside the nth pass."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_weighted_cycle_boolean_verdict","scope":"return-boolean","readMode":"graph-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Sweep every edge up to n times from an all-zero seed, relaxing only on strict improvement, and an improvement on the nth sweep is the negative cycle.","workspacePanel":"code","takeaways":[{"title":"The nth sweep is the whole test","body":"Shortest paths use at most n minus one edges, so a cycle-free graph settles in n minus one sweeps; any improvement on the nth sweep can only come from a loop whose weights total below zero."},{"title":"Seed every node at zero","body":"An all-zero seed plants a launch pad in every component, so a negative cycle is caught even when no single source can reach it."},{"title":"Strict `<`, and the cost is O(n*m)","body":"Relaxing only on a genuine decrease stops a zero-sum loop from looking like an improvement forever; the n sweeps over m edges run in O(n*m), with an early exit the moment a sweep settles."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"hasNegativeCycle","tags":["Bellman-Ford","Shortest Path","Negative Cycle"]}
