{"id":"find-eventual-safe-states","title":"Find Eventual Safe States","difficulty":"medium","patterns":["topological-sort"],"primaryConcept":"graph-toposort-feasibility","concepts":["graph-toposort-feasibility","graph-components"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"graph-adj","primaryParam":"graph","sizeMetric":"nodes-plus-edges","constraints":["directed"]},"description":"You are given a directed graph as an adjacency list `graph`, where `graph[i]` contains every node reachable from node `i` in one step.\n\nA node is eventually safe if every path starting from it eventually reaches a terminal node instead of getting stuck in a cycle. Return all safe nodes in increasing order.","examples":[{"input":"graph = [[1,2],[2,3],[5],[0],[5],[],[]]","output":"[2,4,5,6]","explanation":"Nodes 5 and 6 are terminal. Nodes 2 and 4 can only reach terminal nodes. Nodes 0, 1, and 3 can reach a cycle."},{"input":"graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]","output":"[4]","explanation":"Only node 4 is terminal-safe; the other nodes can reach a cycle."}],"constraints":[{"id":"1-graph-length-10-4","text":"1 <= len(graph) <= 10^4","check":{"kind":"sizeRange","target":"graph","measure":"arrayLength","min":1,"max":10000}},{"id":"0-graph-i-length-graph-length","text":"0 <= len(graph[i]) <= len(graph)","check":{"kind":"valueRange","target":"graph","selector":"arrayItemLengths","min":0,"max":{"sizeOfInput":"graph","measure":"arrayLength"}}},{"id":"0-graph-i-j-graph-length","text":"0 <= graph[i][j] < len(graph)","check":{"kind":"valueRange","target":"graph","selector":"nestedArrayItems","min":0,"max":{"sizeOfInput":"graph","measure":"arrayLength","offset":-1}}},{"id":"graph-i-is-sorted-in-strictly-increasing-order","text":"graph[i] is sorted in strictly increasing order"},{"id":"the-graph-may-contain-cycles","text":"The graph may contain cycles"}],"starterCode":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        # Your code here\n        pass","functionName":"eventualSafeNodes","testCases":[{"id":"1","input":{"graph":[[1,2],[2,3],[5],[0],[5],[],[]]},"expected":[2,4,5,6],"description":"Canonical example with one unsafe cycle."},{"id":"2","input":{"graph":[[1,2,3,4],[1,2],[3,4],[0,4],[]]},"expected":[4],"description":"Only the terminal node is safe."},{"id":"3","input":{"graph":[[],[0],[0,1]]},"expected":[0,1,2],"description":"A directed acyclic graph has all nodes safe."},{"id":"4","input":{"graph":[[1],[2],[0]]},"expected":[],"description":"Every node belongs to a cycle."},{"id":"5","input":{"graph":[[]]},"expected":[0],"description":"Single terminal node."},{"id":"h1","input":{"graph":[[1],[2],[2],[]]},"expected":[3]},{"id":"h2","input":{"graph":[[1],[2],[0],[4],[]]},"expected":[3,4]},{"id":"h3","input":{"graph":[[],[],[]]},"expected":[0,1,2]},{"id":"h4","input":{"graph":[[1,2],[3],[3],[]]},"expected":[0,1,2,3]},{"id":"h5","input":{"graph":[[0]]},"expected":[]},{"id":"topup-1","input":{"graph":[[1,2],[2],[3],[1],[3,5],[]]},"expected":[5],"description":"Top-up case 1: nodes that can reach a cycle are unsafe even if they also branch through other nodes."},{"id":"topup-2","input":{"graph":[[1],[2],[3],[],[4],[4,6],[]]},"expected":[0,1,2,3,6],"description":"Top-up case 2: a safe DAG component coexists with an unsafe self-cycle component."}],"hints":[{"level":1,"content":"Terminal nodes are safe immediately because they have no outgoing edges."},{"level":2,"content":"Reverse the graph so when a node becomes safe, you can update nodes that point into it."},{"level":3,"content":"Track each node's remaining outgoing edge count. When it drops to zero, all of its outgoing paths lead to safe nodes."}],"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":"dfs-coloring","name":"DFS cycle coloring","summary":"Color each node white, gray, or black and run a depth-first walk from every node to detect whether it can reach a gray node still on the stack.","decisionReason":"Three-state DFS identifies the same safe nodes in O(n + e) time. The guided implementation reverses the edges so the queue shows each node becoming safe as its outgoing count reaches zero.","complexity":{"time":"O(n + e)","space":"O(n)"},"tradeoffs":["Same O(n + e) time, but recursive depth can reach the node count on a long chain."],"isViable":true,"isOptimal":false},{"id":"reverse-topology","name":"Reverse topological peeling","summary":"Reverse every edge so terminals become seeds, then peel: record a node safe and lower the outgoing count of each predecessor, queuing it when the count reaches 0.","decisionReason":"It settles each node exactly once with a plain count and a queue, no recursion, which fits the 10^4-node bound directly.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time and uses O(n + e) space for the reverse adjacency."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-reverse-graph","title":"Initialize the reverse graph","description":"Create a reverse adjacency list with one bucket per node.","commonMistakes":["Reusing the original graph buckets","Creating too few reverse buckets"],"hint":"Start with empty reverse buckets; a later step will append predecessor nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Allocate reverse adjacency state for every node before processing edges.","doneWhen":"The reverse graph has one empty neighbor list per node.","shouldFailWhen":"The reverse graph is missing, has the wrong length, or aliases buckets.","roles":["reverse adjacency list","node count"],"mustProve":["The node count is read from the input graph.","An adjacency-style collection is initialized with one bucket per node."],"mustNotAccept":["Using the original graph as the reverse graph.","Creating a single shared neighbor list."],"equivalentVariants":["Use a list comprehension to create empty reverse buckets.","Use an equivalent array or vector of adjacency buckets."],"proofSnippets":[{"id":"py-safe-states-init-reverse-graph","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]"}]}},{"id":"init-outdegree","title":"Initialize outgoing counts","description":"Create a per-node count array that will track how many outgoing edges each node still has.","commonMistakes":["Counting incoming edges instead of outgoing edges","Leaving terminal nodes uninitialized"],"hint":"Terminal nodes are the nodes whose filled outgoing count stays zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize a per-node counter that tracks remaining outgoing edges.","doneWhen":"A count array exists with one entry per node and can be populated from graph[node].length.","shouldFailWhen":"The count array is missing, has the wrong size, or cannot represent terminal nodes as zero.","roles":["outgoing count state","node count","terminal nodes"],"mustProve":["A per-node counter array is initialized.","The counter has one slot for every node."],"mustNotAccept":["A scalar count shared by all nodes.","A counter sized by edge count instead of node count."],"equivalentVariants":["Use a zero-filled list or vector of length n.","Use an equivalent dictionary keyed by node when all nodes are covered."],"proofSnippets":[{"id":"py-safe-states-init-outdegree","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n"}]}},{"id":"count-outgoing-edges","title":"Fill outgoing counts","description":"Set each node's outgoing count from the length of its adjacency list.","commonMistakes":["Leaving every count at zero","Counting incoming edges instead of outgoing edges"],"hint":"For each node, its remaining outgoing count starts as the number of neighbors in graph[node].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"count-outdegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Populate the per-node outgoing count from the original graph.","doneWhen":"The code scans nodes and writes each count from that node's adjacency-list length.","shouldFailWhen":"The code leaves counts at their initialized value, counts the wrong source, or writes every node the same value.","roles":["input graph","node","outgoing count state"],"mustProve":["The code scans nodes from the input graph.","Each node's counter entry is written from graph[node]."],"mustNotAccept":["Leaving the counter array zero-filled.","Sizing the counter array without filling per-node counts."],"equivalentVariants":["Assign indegree[node] = len(graph[node]).","Use an equivalent per-node write from the node's outgoing adjacency list."],"proofSnippets":[{"id":"py-safe-states-count-outgoing-edges","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])"}]}},{"id":"populate-reverse-edges","title":"Reverse each edge","description":"For each original edge node -> neighbor, append node to reverse[neighbor].","commonMistakes":["Appending neighbor to reverse[node]","Walking a temporary graph instead of the input graph"],"hint":"The reverse graph stores predecessors, so neighbor's bucket receives node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"reverse-edges","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Populate reverse adjacency buckets from the input graph's directed edges.","doneWhen":"The code scans original graph edges and appends each source node into the neighbor's reverse bucket.","shouldFailWhen":"The code skips edge reversal, appends into the wrong bucket, or uses a non-input edge source.","roles":["input graph","source node","neighbor","reverse adjacency list"],"mustProve":["The code scans edges from the input graph.","For each edge, the source node is appended to the neighbor's reverse bucket."],"mustNotAccept":["Only allocating reverse buckets.","Appending neighbor to reverse[node]."],"equivalentVariants":["Use reverse[neighbor].append(node).","Use an equivalent predecessor-list update for each original edge."],"proofSnippets":[{"id":"py-safe-states-populate-reverse-edges","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)"}]}},{"id":"seed-terminal-frontier","title":"Seed terminal nodes","description":"Push every node whose outgoing count is zero into the queue.","commonMistakes":["Seeding nodes with nonzero outgoing edges","Only seeding the first terminal node"],"hint":"Terminal nodes are already safe because they cannot reach a cycle.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize the processing frontier with all zero-count terminal nodes.","doneWhen":"Every node whose outgoing count is zero is appended to the queue before the peeling loop.","shouldFailWhen":"The queue misses terminal nodes or includes nodes that still have outgoing edges.","roles":["zero outgoing count","queue","terminal node"],"mustProve":["The code scans the node count.","The queue receives nodes whose count is zero."],"mustNotAccept":["Hardcoding one terminal node.","Seeding from the original graph without checking the count."],"equivalentVariants":["Use a list queue with append.","Use a deque or queue abstraction."],"proofSnippets":[{"id":"py-safe-states-seed-terminal-frontier","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)"}]}},{"id":"record-safe-node","title":"Record each safe node","description":"As nodes leave the queue, record them as safe.","commonMistakes":["Recording predecessors before their outgoing count reaches zero","Forgetting to record terminal nodes"],"hint":"A queued node is safe because all of its outgoing paths have already been proven safe.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Collect every node removed from the terminal-safe frontier.","doneWhen":"The BFS/topological loop appends each popped node to the safe result list.","shouldFailWhen":"The result is not updated from the queue loop or records nodes before they are proven safe.","roles":["queue node","safe result list","topological peel order"],"mustProve":["The code processes queued nodes.","Each processed node is appended to a result collection."],"mustNotAccept":["Returning all nodes without processing the queue.","Recording neighbors before their counts reach zero."],"equivalentVariants":["Append each popped node to a result list.","Mark each popped node in a boolean safe array and derive the result later."],"proofSnippets":[{"id":"py-safe-states-record-safe-node","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)"}]}},{"id":"update-predecessors","title":"Peel predecessor counts","description":"For each safe node, decrement the outgoing count of every predecessor and enqueue it when the count reaches zero.","commonMistakes":["Walking original outgoing edges instead of reverse predecessors","Enqueuing a predecessor before all outgoing edges are safe"],"hint":"A predecessor becomes safe only after every outgoing edge points to a safe node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Propagate safety backward through reverse edges by decrementing predecessor counts.","doneWhen":"Every predecessor of a safe node has its remaining count decremented and is enqueued exactly when that count reaches zero.","shouldFailWhen":"The code decrements the wrong node, skips reverse predecessors, or enqueues before the zero-count condition.","roles":["reverse predecessor","outgoing count","zero-count enqueue"],"mustProve":["The loop traverses reverse neighbors of the safe node.","The predecessor count is decremented.","The predecessor is enqueued only when the count reaches zero."],"mustNotAccept":["Walking original outgoing edges in this step.","Appending every predecessor unconditionally."],"equivalentVariants":["Use reverse adjacency buckets and a count decrement.","Use any equivalent predecessor list that supports the same zero-count enqueue."],"proofSnippets":[{"id":"py-safe-states-update-predecessors","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)\n            for prev in reverse[node]:\n                indegree[prev] -= 1\n                if indegree[prev] == 0:\n                    queue.append(prev)"}]}},{"id":"return-safe-nodes","title":"Return safe nodes in order","description":"Return the collected safe nodes sorted in increasing node id order.","commonMistakes":["Returning the queue order without sorting","Returning unsafe nodes that never reached zero outgoing count"],"hint":"The problem asks for increasing order, but the reverse peel order can be different.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the final sequence of safe node ids in increasing order.","doneWhen":"The function returns the collected safe nodes after sorting or otherwise producing increasing order.","shouldFailWhen":"The code returns a scalar, the original graph, or an unsorted peel-order list when order can differ.","roles":["safe result list","increasing order","returned sequence"],"mustProve":["The returned value is derived from the safe-node result collection.","The result is ordered before return."],"mustNotAccept":["Returning all nodes regardless of safety.","Returning the reverse graph or count array."],"equivalentVariants":["Return sorted(safe).","Collect safe nodes in a boolean array and emit indices in increasing order."],"proofSnippets":[{"id":"py-safe-states-return-safe-nodes","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)\n            for prev in reverse[node]:\n                indegree[prev] -= 1\n                if indegree[prev] == 0:\n                    queue.append(prev)\n\n        return sorted(safe)"}]}}],"slides":[{"id":"read-the-signal","chapter":"The graph","kind":"info","eyebrow":"Read the problem","title":"Find the nodes that can never get stuck","workspacePanel":"problem","body":["You are given a directed graph as an adjacency list. graph[i] lists every node you can step to from node i in one move. A node is safe if every path leaving it eventually dead-ends at a terminal node, never circling back into a cycle.","A node is safe only when every path from it avoids every cycle. One outgoing edge into an unsafe region makes the node unsafe too."]},{"id":"naive-scan","chapter":"The graph","kind":"code-trace","eyebrow":"The obvious way","title":"Mark a node safe when all its edges point to safe nodes, and repeat","summary":"It answers correctly, but a single pass only catches nodes whose targets are already safe, so it has to loop until a full pass changes nothing. Watch how many times the same edges get re-read.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"safe = [False] * len(graph)\nchanged = True\nwhile changed:\n    changed = False\n    for node in range(len(graph)):\n        if safe[node]:\n            continue\n        all_safe = True\n        for nxt in graph[node]:\n            if safe[nxt] == False:\n                all_safe = False\n        if all_safe:\n            safe[node] = True\n            changed = True\nreturn [node for node in range(len(graph)) if safe[node]]","steps":[{"id":"pass-one-terminals","title":"First pass: only the terminals have all edges safe","codeLine":5,"summary":"Scan all seven nodes. Only 5 and 6 have no edges, so their all_safe check passes and they are marked. Nodes 0 through 4 each fail because their targets are not safe yet.","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":5,"visited":[5,6]}}},{"id":"pass-two-rescan","title":"Second pass re-scans every node from scratch","codeLine":5,"summary":"Something changed, so loop again. Nodes 0 through 4 are re-checked, re-reading every edge list, even though only 5 and 6 became safe last pass. Now node 2 and node 4 pass.","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":2,"visited":[5,6,2,4]}}},{"id":"pass-three-stall","title":"A third pass changes nothing, so it stops","codeLine":3,"summary":"Re-scan once more. Nodes 0, 1, and 3 still have an edge into the cycle, so none of them flips. No change this pass, so the loop ends with 2, 4, 5, 6 marked safe.","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":0,"visited":[5,6,2,4],"highlighted":[0,1,3]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const safe = Array(graph.length).fill(false);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let node = 0; node < graph.length; node++) {\n        if (safe[node]) {\n            continue;\n        }\n        let allSafe = true;\n        for (const nxt of graph[node]) {\n            if (safe[nxt] === false) {\n                allSafe = false;\n            }\n        }\n        if (allSafe) {\n            safe[node] = true;\n            changed = true;\n        }\n    }\n}\nreturn Array.from({ length: graph.length }, (_, index) => index).filter((node) => safe[node]);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14},"14":{"startLine":17,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const safe = Array(graph.length).fill(false);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let node = 0; node < graph.length; node++) {\n        if (safe[node]) {\n            continue;\n        }\n        let allSafe = true;\n        for (const nxt of graph[node]) {\n            if (safe[nxt] === false) {\n                allSafe = false;\n            }\n        }\n        if (allSafe) {\n            safe[node] = true;\n            changed = true;\n        }\n    }\n}\nreturn Array.from({ length: graph.length }, (_, index) => index).filter((node) => safe[node]);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14},"14":{"startLine":17,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Boolean> safe = new ArrayList<>();\nfor (int index = 0; index < graph.size(); index++) {\n    safe.add(false);\n}\nboolean changed = true;\nwhile (changed) {\n    changed = false;\n    for (int node = 0; node < graph.size(); node++) {\n        if (safe.get(node)) {\n            continue;\n        }\n        boolean allSafe = true;\n        for (Integer nxt : graph.get(node)) {\n            if (Objects.equals(safe.get(nxt), false)) {\n                allSafe = false;\n            }\n        }\n        if (allSafe) {\n            safe.set(node, true);\n            changed = true;\n        }\n    }\n}\nreturn java.util.stream.IntStream.range(0, graph.size()).boxed().filter(node -> safe.get(node)).collect(java.util.stream.Collectors.toList());","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":10,"8":12,"9":13,"10":14,"11":15,"12":18,"13":19,"14":20,"15":24},"statementBundles":{"1":{"startLine":1,"endLine":4},"7":{"startLine":10,"endLine":11},"11":{"startLine":15,"endLine":17},"14":{"startLine":20,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<bool> safe = Enumerable.Repeat<bool>(false, graph.Count).ToList();\nbool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int node = 0; node < graph.Count; node++) {\n        if (safe[node]) {\n            continue;\n        }\n        bool allSafe = true;\n        foreach (int nxt in graph[node]) {\n            if (safe[nxt] == false) {\n                allSafe = false;\n            }\n        }\n        if (allSafe) {\n            safe[node] = true;\n            changed = true;\n        }\n    }\n}\nreturn Enumerable.Range(0, graph.Count).Where(node => safe[node]).Select(node => node).ToList();","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14},"14":{"startLine":17,"endLine":20}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<bool> safe = vector<bool>(graph.size(), false);\nbool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int node = 0; node < graph.size(); node++) {\n        if (safe[node]) {\n            continue;\n        }\n        bool all_safe = true;\n        for (int nxt : graph[node]) {\n            if (safe[nxt] == false) {\n                all_safe = false;\n            }\n        }\n        if (all_safe) {\n            safe[node] = true;\n            changed = true;\n        }\n    }\n}\nvector<int> result;\nfor (int node = 0; node < graph.size(); node++) {\n    if (safe[node]) {\n        result.push_back(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15,"13":16,"14":17,"15":21},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14},"14":{"startLine":17,"endLine":20},"15":{"startLine":21,"endLine":27}}}}}},{"id":"naive-cost","chapter":"The graph","kind":"case-probe","eyebrow":"Count the work","title":"How much does each pass cost, and how many passes run?","summary":"The sample took three passes to settle. Picture the same pattern on a long chain instead.","workspacePanel":"trace","options":[{"id":"rescan-per-pass","label":"Every pass re-reads all the edges of every unmarked node, and a long chain forces one pass per layer","rationale":"Each pass walks every unmarked node and re-reads its whole edge list. Safety spreads only one layer per pass, so a chain of length n needs about n passes, and the same edges get re-read over and over.","isCorrect":true},{"id":"one-pass","label":"One pass over the nodes is enough to mark every safe node","rationale":"A node usually is not markable on the first pass. Node 2 only becomes safe after 5 is marked, which takes a second pass, and deeper chains take more.","isCorrect":false},{"id":"fixed-passes","label":"A fixed two or three passes always suffice","rationale":"The number of passes grows with the longest dependency chain. A chain of n nodes needs about n passes.","isCorrect":false}],"answer":"Each pass re-reads every unmarked node’s edges, and safety spreads only one layer per pass, so a chain of length n forces about n passes that re-scan the same edges over and over."},{"id":"safe-from-terminals","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Terminal nodes are the dead-ends","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"shape","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"queue":[5,6]}}}]},"body":["The number beside each node is its outdegree, how many outgoing edges it has. Most nodes carry one or two; nodes 5 and 6 sit at 0, with nowhere left to step.","Those zero-count nodes have no outgoing edges, so they give the peel its starting queue."]},{"id":"state-enough","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"What do you need to track to decide a node is safe?","summary":"The naive walk re-reads paths after each new safe node.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"highlighted":[5,6]}}}]},"options":[{"id":"remaining-outgoing","label":"A count per node of how many of its outgoing edges do not yet lead to a node proven safe","rationale":"A node is safe the instant that count reaches 0: every edge it has leads somewhere safe. Proving a node safe just lowers that count for the nodes pointing at it, with no re-walk.","isCorrect":true},{"id":"full-paths","label":"The full list of paths leaving each node","rationale":"That is what the naive walk re-traced every time. Once you only ask whether the outgoing count has hit 0, the individual paths no longer matter.","isCorrect":false},{"id":"visit-flag","label":"A visited flag marking each node the search has touched","rationale":"Visiting a node says nothing about whether its paths end safely. Nodes 0 and 1 both get visited, yet both reach the cycle.","isCorrect":false}],"answer":"A per-node count of outgoing edges still leading to unproven nodes. A node is safe the moment that count hits 0, so one number replaces every re-walk."},{"id":"terminal-first","chapter":"The idea","kind":"case-probe","eyebrow":"Find the start","title":"Which nodes are safe before any work is done?","summary":"Before any updates, each node still carries its original outgoing count.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"terminals","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"queue":[5,6]}}}]},"options":[{"id":"terminals","label":"Nodes 5 and 6, the terminal nodes with no outgoing edges","rationale":"With nowhere to step, a terminal node has no path that could ever loop. Its outgoing count is already 0, so it is safe from the start.","isCorrect":true},{"id":"lowest-id","label":"Node 0, because it has the smallest id","rationale":"Id order has nothing to do with safety. Node 0 steps to 1 and 2 and can circle back through 3, so it is one of the unsafe nodes.","isCorrect":false},{"id":"most-edges","label":"The node with the most outgoing edges, since it has the most ways out","rationale":"More edges means more ways to reach a cycle, not fewer. Safety begins at the dead-ends, where there are no edges at all.","isCorrect":false}],"answer":"Nodes 5 and 6. A terminal node has outgoing count 0, so it cannot reach a cycle and is safe immediately. They are the seeds everything else peels back from."},{"id":"all-edges-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"One of node 0’s two edges now leads to a safe node. Is node 0 safe?","summary":"Node 2 was just proven safe, and node 0 started with two outgoing edges.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"one-edge-cleared","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":2,"visited":[2,4,5,6],"activeEdges":[[0,2]],"highlighted":[0]}}}]},"options":[{"id":"still-unsafe","label":"No: its other edge, into node 1, still has not been cleared","rationale":"Node 0 also steps to 1, and 1 sits on the cycle 0 -> 1 -> 0. That edge keeps node 0’s count at 1, so node 0 stays unsafe. A node is safe only when every outgoing edge leads to safety.","isCorrect":true},{"id":"one-is-enough","label":"Yes: it now has a path to a safe node","rationale":"Having one safe path is not enough. Node 0 can still step to 1 and loop forever, so a single cleared edge cannot make it safe.","isCorrect":false},{"id":"count-zero","label":"Yes: its count already reached 0","rationale":"Its count is 1, not 0. Only the edge to node 2 cleared; the edge to node 1 is still waiting, so the count has not bottomed out.","isCorrect":false}],"answer":"No. Node 0’s count is 1, not 0: its edge to node 1 still reaches the cycle. A node becomes safe only when every one of its outgoing edges has been cleared to a safe node."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"queue":[5,6]}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Peel safety back through reverse edges","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"queue":[5,6],"activeEdges":[[2,5],[4,5],[4,6]]}}}]},"body":["A queue holds every node whose outgoing count is currently 0. It starts with the terminals, 5 and 6.","Pop a node, record it as safe, and for every node that points into it, drop that node’s outgoing count by one. Any node whose count reaches 0 joins the queue.","When the queue runs dry, the recorded nodes are exactly the safe ones."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the peel","title":"Peel the safe nodes","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pop-5","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":5,"visited":[5],"queue":[6,2],"highlighted":[2,4],"activeEdges":[[2,5],[4,5]]}}},{"id":"pop-2","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":2,"visited":[5,6,2],"queue":[4],"highlighted":[0],"activeEdges":[[0,2]]}}},{"id":"pop-4","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"current":4,"visited":[5,6,2,4],"queue":[]}}},{"id":"stuck","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"visited":[5,6,2,4],"queue":[],"highlighted":[0,1,3]}}}]},"beats":[{"id":"pop-5","title":"Node 5 is recorded safe. Which nodes have a count to drop?","summary":"Node 5 comes off the queue first.","prompt":"Inspect node 5's reverse list.","options":[{"id":"two-four","label":"Nodes 2 and 4, which both point into node 5","rationale":"Both step into 5. Node 2 drops from 1 to 0 and joins the queue. Node 4 drops from 2 to 1, since it still owes its edge to terminal 6.","isCorrect":true},{"id":"all-in","label":"Every node, since 5 is now safe","rationale":"Only the nodes with an edge directly into 5 lower their count. Nodes 0, 1, and 3 do not point at 5, so they are untouched.","isCorrect":false},{"id":"none-yet","label":"None until every terminal is processed","rationale":"A node’s count drops the moment one of its targets is proven safe. Node 2 comes due as soon as 5 is recorded.","isCorrect":false}],"answer":"Nodes 2 and 4 each lose their edge into 5. Node 2 reaches 0 and queues; node 4 drops to 1 and clears once terminal 6 is popped too."},{"id":"pop-2","title":"Node 2 is recorded safe. What happens to node 0’s count?","summary":"The next safe item is processed.","prompt":"Use the count after removing one cleared edge.","options":[{"id":"drops-to-one","label":"It drops from 2 to 1 but node 0 does not enter the queue","rationale":"Node 0’s edge to 2 clears, but its edge to 1 remains. Count 1 is not 0, so node 0 stays off the queue.","isCorrect":true},{"id":"drops-to-zero","label":"It drops to 0 and node 0 joins the queue","rationale":"Only one of node 0’s two edges cleared. The edge to node 1 still counts, so node 0 sits at 1, not 0.","isCorrect":false},{"id":"untouched","label":"Nothing, node 0 does not point into node 2","rationale":"Node 0 lists 2 among its targets, so recording 2 safe does lower node 0’s count.","isCorrect":false}],"answer":"Node 0 drops to 1. Its edge to node 1 still leads into the cycle, so it stays unsafe for now."},{"id":"pop-4","title":"Node 4 is recorded and the queue is now empty. Is node 0 safe?","summary":"Node 4 points only into the terminals, so popping it adds no one new and the queue drains.","prompt":"Check node 0’s count now that the queue is empty.","options":[{"id":"no-stuck","label":"No: its count never reached 0","rationale":"Node 0 still has an outgoing edge to node 1, whose count is stuck at 2. Node 0 can step into the cycle, so it is unsafe.","isCorrect":true},{"id":"yes-eventually","label":"Yes: every node clears once the queue drains","rationale":"Draining the queue does not clear stuck counts. Nodes 0, 1, and 3 hold each other above 0 through the cycle and never queue.","isCorrect":false},{"id":"depends-order","label":"Only if node 0 had been processed earlier","rationale":"Order cannot rescue it. Node 0 depends on node 1 clearing, which depends back on node 0 through the cycle.","isCorrect":false}],"answer":"No. Nodes 0 and 1 form a cycle and node 3 steps into it, so their counts never reach 0 and none of them queue. They are the unsafe nodes."},{"id":"stuck","title":"When the queue is empty, what is the final answer?","summary":"Three nodes never cleared; the queue holds nothing more to peel.","prompt":"The nodes came off the queue as 5, 6, 2, 4.","options":[{"id":"sorted-four","label":"The recorded nodes in increasing order: [2, 4, 5, 6]","rationale":"The four nodes that hit count 0 are the safe ones. The problem asks for increasing order, so the peel order 5, 6, 2, 4 is sorted before returning.","isCorrect":true},{"id":"peel-order","label":"The nodes in the order they were recorded: [5, 6, 2, 4]","rationale":"Those are the right nodes but the wrong order. The answer must be in increasing node id order, so it needs sorting.","isCorrect":false},{"id":"all-seven","label":"All seven nodes, since the process finished","rationale":"Nodes 0, 1, and 3 never reached count 0, so they are unsafe and must be left out.","isCorrect":false}],"answer":"The four recorded nodes, sorted: [2, 4, 5, 6]. The trapped cycle nodes 0, 1, 3 never cleared."}]},{"id":"enqueue-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you just lower the counts and skip re-queuing?","summary":"This version builds reverse edges and lowers each predecessor’s count, so the first terminal looks handled. It tries to let the counts speak for themselves. Watch it on a three-node chain where every node is safe.","workspacePanel":"trace","pitfall":"The code lowers predecessor counts but never enqueues a node when its count reaches 0, so the queue empties after the first wave and later nodes are never recorded.","whyItMatters":"Lowering a count is only half the move. The instant a node’s count hits 0 it has to join the queue, or the peel stops after one layer and safe nodes deeper in the chain are reported unsafe. Enqueue every predecessor whose count just reached 0.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"reverse = [[] for _ in range(len(graph))]\noutdegree = [0] * len(graph)\nfor node in range(len(graph)):\n    outdegree[node] = len(graph[node])\n    for nxt in graph[node]:\n        reverse[nxt].append(node)\nqueue = [node for node in range(len(graph)) if outdegree[node] == 0]\nsafe = []\nhead = 0\nwhile head < len(queue):\n    node = queue[head]\n    head += 1\n    safe.append(node)\n    for prev in reverse[node]:\n        outdegree[prev] -= 1\nreturn sorted(safe)","steps":[{"id":"seed-terminal","title":"Only the terminal node seeds the queue","codeLine":7,"summary":"graph = [[1],[2],[]]. Node 2 is terminal with count 0; nodes 0 and 1 sit at 1. The queue starts with just node 2.","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 0"}],"edges":[[0,1],[1,2]],"queue":[2]}}},{"id":"drop-one","title":"Node 2 is recorded and node 1 drops to 0","codeLine":15,"summary":"Node 2 is recorded safe. Its only predecessor, node 1, drops from 1 to 0. But nothing puts node 1 back on the queue.","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"}],"edges":[[0,1],[1,2]],"current":2,"visited":[2],"queue":[],"highlighted":[1],"activeEdges":[[1,2]]}}},{"id":"stops-short","title":"The queue is empty, so the peel stops at node 2","codeLine":16,"summary":"Node 1 sits at count 0 but never entered the queue, so node 0 is never relieved. The result is [2] on a chain where all three nodes are safe.","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"}],"edges":[[0,1],[1,2]],"visited":[2],"queue":[]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const reverse = Array.from({ length: graph.length }, () => []);\nconst outdegree = Array(graph.length).fill(0);\nfor (let node = 0; node < graph.length; node++) {\n    outdegree[node] = graph[node].length;\n    for (const nxt of graph[node]) {\n        reverse[nxt].push(node);\n    }\n}\nconst queue = Array.from({ length: graph.length }, (_, index) => index).filter((node) => outdegree[node] === 0);\nconst safe = [];\nlet head = 0;\nwhile (head < queue.length) {\n    const node = queue[head];\n    head++;\n    safe.push(node);\n    for (const prev of reverse[node]) {\n        outdegree[prev] = (outdegree[prev] - 1);\n    }\n}\nreturn [...safe].sort((a, b) => a - b);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":20},"statementBundles":{"6":{"startLine":6,"endLine":8},"15":{"startLine":17,"endLine":19}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const reverse: Array<Array<number>> = Array.from({ length: graph.length }, () => []);\nconst outdegree = Array(graph.length).fill(0);\nfor (let node = 0; node < graph.length; node++) {\n    outdegree[node] = graph[node].length;\n    for (const nxt of graph[node]) {\n        reverse[nxt].push(node);\n    }\n}\nconst queue = Array.from({ length: graph.length }, (_, index) => index).filter((node) => outdegree[node] === 0);\nconst safe: Array<number> = [];\nlet head = 0;\nwhile (head < queue.length) {\n    const node = queue[head];\n    head++;\n    safe.push(node);\n    for (const prev of reverse[node]) {\n        outdegree[prev] = (outdegree[prev] - 1);\n    }\n}\nreturn [...safe].sort((a, b) => a - b);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":20},"statementBundles":{"6":{"startLine":6,"endLine":8},"15":{"startLine":17,"endLine":19}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> reverse = new ArrayList<>();\nfor (int i = 0; i < graph.size(); i++) {\n    reverse.add(new ArrayList<>());\n}\nint[] outdegree = new int[graph.size()];\nfor (int node = 0; node < graph.size(); node++) {\n    outdegree[node] = graph.get(node).size();\n    for (Integer nxt : graph.get(node)) {\n        reverse.get(nxt).add(node);\n    }\n}\nList<Integer> queue = new ArrayList<>();\nfor (int node = 0; node < graph.size(); node++) {\n    if (outdegree[node] == 0) {\n        queue.add(node);\n    }\n}\nList<Integer> safe = new ArrayList<>();\nint head = 0;\nwhile (head < queue.size()) {\n    int node = queue.get(head);\n    head++;\n    safe.add(node);\n    for (Integer prev : reverse.get(node)) {\n        outdegree[prev] = (outdegree[prev] - 1);\n    }\n}\nreturn safe.stream().sorted().collect(java.util.stream.Collectors.toCollection(ArrayList::new));","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":12,"8":18,"9":19,"10":20,"11":21,"12":22,"13":23,"14":24,"15":25,"16":28},"statementBundles":{"1":{"startLine":1,"endLine":4},"6":{"startLine":9,"endLine":11},"7":{"startLine":12,"endLine":17},"15":{"startLine":25,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> reverse = Enumerable.Range(0, graph.Count).Select(_ => new List<int>()).ToList();\nList<int> outdegree = Enumerable.Repeat<int>(0, graph.Count).ToList();\nfor (int node = 0; node < graph.Count; node++) {\n    outdegree[node] = graph[node].Count;\n    foreach (int nxt in graph[node]) {\n        reverse[nxt].Add(node);\n    }\n}\nList<int> queue = Enumerable.Range(0, graph.Count).Where(node => outdegree[node] == 0).Select(node => node).ToList();\nList<int> safe = new();\nint head = 0;\nwhile (head < queue.Count) {\n    int node = queue[head];\n    head++;\n    safe.Add(node);\n    foreach (int prev in reverse[node]) {\n        outdegree[prev] = outdegree[prev] - 1;\n    }\n}\nreturn safe.OrderBy(value => value).ToList();","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":20},"statementBundles":{"6":{"startLine":6,"endLine":8},"15":{"startLine":17,"endLine":19}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> reverse = vector<vector<int>>(graph.size(), vector<int>{});\nvector<int> outdegree = vector<int>(graph.size(), 0);\nfor (int node = 0; node < graph.size(); node++) {\n    outdegree[node] = graph[node].size();\n    for (int nxt : graph[node]) {\n        reverse[nxt].push_back(node);\n    }\n}\nvector<int> queue;\nfor (int node = 0; node < graph.size(); node++) {\n    if (outdegree[node] == 0) {\n        queue.push_back(node);\n    }\n}\nvector<int> safe;\nsize_t head = 0;\nwhile (head < queue.size()) {\n    int node = queue[static_cast<int>(head)];\n    head++;\n    safe.push_back(node);\n    for (int prev : reverse[node]) {\n        outdegree[prev] = (outdegree[prev] - 1);\n    }\n}\nvector<int> sorted_items = safe;\nstable_sort(sorted_items.begin(), sorted_items.end());\nreturn sorted_items;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9,"8":15,"9":16,"10":17,"11":18,"12":19,"13":20,"14":21,"15":22,"16":25},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":14},"15":{"startLine":22,"endLine":24},"16":{"startLine":25,"endLine":27}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"visited":[2,4,5,6],"highlighted":[0,1,3]}}}]},"body":["Peeling from the terminals cleared the sample graph, every safe node coming off the queue until only the cycle nodes were left.","Two thin graphs are worth poking at before you code: one where every node sits on a cycle, and one where a node points straight at itself."]},{"id":"all-cycle-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if every node sits on one big cycle?","summary":"graph = [[1],[2],[0]], a single loop 0 -> 1 -> 2 -> 0.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-cycle","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 1"}],"edges":[[0,1],[1,2],[2,0]]}}}]},"options":[{"id":"empty","label":"No node is safe, so the answer is empty","rationale":"Every node has outgoing count 1 and no terminal exists, so the queue starts empty. Nothing ever reaches count 0, and no node is recorded.","isCorrect":true},{"id":"all-safe","label":"All three are safe once the cycle is fully visited","rationale":"Visiting a node does not make it safe. None of these counts ever reaches 0, so the peel records nothing.","isCorrect":false},{"id":"first-node","label":"Only node 0, the entry into the cycle","rationale":"There is no entry that escapes. Node 0 steps to 1, which steps to 2, which steps back to 0, so 0 can loop forever.","isCorrect":false}],"answer":"Empty. With no terminal, the queue never seeds, every count stays at 1, and no node is recorded safe."},{"id":"self-loop-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What about a node that points at itself?","summary":"graph = [[0]], one node with an edge back to itself.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"self-loop","state":{"graph":{"nodes":[{"id":0,"label":"0: 1"}],"edges":[[0,0]]}}}]},"options":[{"id":"unsafe","label":"It is unsafe: its count starts at 1 and never drops","rationale":"A self-edge is its own one-node cycle. The node’s outgoing count is 1, and the only way to clear it is for the node itself to become safe first, which never happens.","isCorrect":true},{"id":"terminal","label":"It is safe, since it is the only node in the graph","rationale":"Being alone does not make it terminal. It has an outgoing edge, so its count is 1, not 0, and it can step forever onto itself.","isCorrect":false},{"id":"crash","label":"It loops forever and the peel never terminates","rationale":"The peel only processes nodes that reach count 0. This node never does, so it is simply never queued and the loop ends normally with an empty result.","isCorrect":false}],"answer":"Unsafe. A self-edge keeps the count at 1 forever, so the node is never queued and the answer is empty."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two things to keep straight: a node is recorded only when its outgoing count reaches 0, and the peel order is not id order, so sort before returning.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"graph":{"nodes":[{"id":0,"label":"0: 2"},{"id":1,"label":"1: 2"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 0"},{"id":6,"label":"6: 0"}],"edges":[[0,1],[0,2],[1,0],[1,3],[2,5],[3,1],[4,5],[4,6]],"queue":[5,6]}}}]},"body":["Safety flows backward: once a node is proven safe, the only nodes that could newly qualify are the ones pointing into it, so reversed edges carry the news to exactly those predecessors.","Each node’s remaining outgoing count is the invariant. The terminal nodes, already at zero, are the starting frontier, and a node joins them the moment its count drains to zero. Return the safe ids in increasing order."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the reverse peel","summary":"Now build it: reverse the edges into a bucket per node, count each node's outgoing edges, seed the queue with the terminals, then peel by recording each node you pop, dropping the count of every predecessor and queuing it the instant that count hits 0, and return the recorded nodes sorted.","workspacePanel":"code","checkpoints":[{"id":"init-reverse-graph","title":"Initialize the reverse graph","description":"Create a reverse adjacency list with one bucket per node.","commonMistakes":["Reusing the original graph buckets","Creating too few reverse buckets"],"hint":"Each original edge node -> neighbor becomes reverse edge neighbor -> node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Allocate reverse adjacency state for every node before processing edges.","doneWhen":"The reverse graph has one empty neighbor list per node.","shouldFailWhen":"The reverse graph is missing, has the wrong length, or aliases buckets.","roles":["reverse adjacency list","node count"],"mustProve":["The node count is read from the input graph.","An adjacency-style collection is initialized with one bucket per node."],"mustNotAccept":["Using the original graph as the reverse graph.","Creating a single shared neighbor list."],"equivalentVariants":["Use a list comprehension to create empty reverse buckets.","Use an equivalent array or vector of adjacency buckets."],"proofSnippets":[{"id":"py-safe-states-init-reverse-graph","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]"}]}},{"id":"init-outdegree","title":"Initialize outgoing counts","description":"Create a count array for how many outgoing edges each node still has.","commonMistakes":["Counting incoming edges instead of outgoing edges","Leaving terminal nodes uninitialized"],"hint":"A node with zero outgoing edges is terminal and safe first.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize a per-node counter that tracks remaining outgoing edges.","doneWhen":"A count array exists with one entry per node and can be populated from graph[node].length.","shouldFailWhen":"The count array is missing, has the wrong size, or cannot represent terminal nodes as zero.","roles":["outgoing count state","node count","terminal nodes"],"mustProve":["A per-node counter array is initialized.","The counter has one slot for every node."],"mustNotAccept":["A scalar count shared by all nodes.","A counter sized by edge count instead of node count."],"equivalentVariants":["Use a zero-filled list or vector of length n.","Use an equivalent dictionary keyed by node when all nodes are covered."],"proofSnippets":[{"id":"py-safe-states-init-outdegree","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n"}]}},{"id":"count-outgoing-edges","title":"Fill outgoing counts","description":"Set each node's outgoing count from the length of its adjacency list.","commonMistakes":["Leaving every count at zero","Counting incoming edges instead of outgoing edges"],"hint":"For each node, its remaining outgoing count starts as the number of neighbors in graph[node].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"count-outdegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Populate the per-node outgoing count from the original graph.","doneWhen":"The code scans nodes and writes each count from that node's adjacency-list length.","shouldFailWhen":"The code leaves counts at their initialized value, counts the wrong source, or writes every node the same value.","roles":["input graph","node","outgoing count state"],"mustProve":["The code scans nodes from the input graph.","Each node's counter entry is written from graph[node]."],"mustNotAccept":["Leaving the counter array zero-filled.","Sizing the counter array without filling per-node counts."],"equivalentVariants":["Assign indegree[node] = len(graph[node]).","Use an equivalent per-node write from the node's outgoing adjacency list."],"proofSnippets":[{"id":"py-safe-states-count-outgoing-edges","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])"}]}},{"id":"populate-reverse-edges","title":"Reverse each edge","description":"For each original edge node -> neighbor, append node to reverse[neighbor].","commonMistakes":["Appending neighbor to reverse[node]","Walking a temporary graph instead of the input graph"],"hint":"The reverse graph stores predecessors, so neighbor's bucket receives node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"reverse-edges","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Populate reverse adjacency buckets from the input graph's directed edges.","doneWhen":"The code scans original graph edges and appends each source node into the neighbor's reverse bucket.","shouldFailWhen":"The code skips edge reversal, appends into the wrong bucket, or uses a non-input edge source.","roles":["input graph","source node","neighbor","reverse adjacency list"],"mustProve":["The code scans edges from the input graph.","For each edge, the source node is appended to the neighbor's reverse bucket."],"mustNotAccept":["Only allocating reverse buckets.","Appending neighbor to reverse[node]."],"equivalentVariants":["Use reverse[neighbor].append(node).","Use an equivalent predecessor-list update for each original edge."],"proofSnippets":[{"id":"py-safe-states-populate-reverse-edges","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)"}]}},{"id":"seed-terminal-frontier","title":"Seed terminal nodes","description":"Push every node whose outgoing count is zero into the queue.","commonMistakes":["Seeding nodes with nonzero outgoing edges","Only seeding the first terminal node"],"hint":"Terminal nodes are already safe because they cannot reach a cycle.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Initialize the processing frontier with all zero-count terminal nodes.","doneWhen":"Every node whose outgoing count is zero is appended to the queue before the peeling loop.","shouldFailWhen":"The queue misses terminal nodes or includes nodes that still have outgoing edges.","roles":["zero outgoing count","queue","terminal node"],"mustProve":["The code scans the node count.","The queue receives nodes whose count is zero."],"mustNotAccept":["Hardcoding one terminal node.","Seeding from the original graph without checking the count."],"equivalentVariants":["Use a list queue with append.","Use a deque or queue abstraction."],"proofSnippets":[{"id":"py-safe-states-seed-terminal-frontier","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)"}]}},{"id":"record-safe-node","title":"Record each safe node","description":"As nodes leave the queue, record them as safe.","commonMistakes":["Recording predecessors before their outgoing count reaches zero","Forgetting to record terminal nodes"],"hint":"A queued node is safe because all of its outgoing paths have already been proven safe.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Collect every node removed from the terminal-safe frontier.","doneWhen":"The BFS/topological loop appends each popped node to the safe result list.","shouldFailWhen":"The result is not updated from the queue loop or records nodes before they are proven safe.","roles":["queue node","safe result list","topological peel order"],"mustProve":["The code processes queued nodes.","Each processed node is appended to a result collection."],"mustNotAccept":["Returning all nodes without processing the queue.","Recording neighbors before their counts reach zero."],"equivalentVariants":["Append each popped node to a result list.","Mark each popped node in a boolean safe array and derive the result later."],"proofSnippets":[{"id":"py-safe-states-record-safe-node","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)"}]}},{"id":"update-predecessors","title":"Peel predecessor counts","description":"For each safe node, decrement the outgoing count of every predecessor and enqueue it when the count reaches zero.","commonMistakes":["Walking original outgoing edges instead of reverse predecessors","Enqueuing a predecessor before all outgoing edges are safe"],"hint":"A predecessor becomes safe only after every outgoing edge points to a safe node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Propagate safety backward through reverse edges by decrementing predecessor counts.","doneWhen":"Every predecessor of a safe node has its remaining count decremented and is enqueued exactly when that count reaches zero.","shouldFailWhen":"The code decrements the wrong node, skips reverse predecessors, or enqueues before the zero-count condition.","roles":["reverse predecessor","outgoing count","zero-count enqueue"],"mustProve":["The loop traverses reverse neighbors of the safe node.","The predecessor count is decremented.","The predecessor is enqueued only when the count reaches zero."],"mustNotAccept":["Walking original outgoing edges in this step.","Appending every predecessor unconditionally."],"equivalentVariants":["Use reverse adjacency buckets and a count decrement.","Use any equivalent predecessor list that supports the same zero-count enqueue."],"proofSnippets":[{"id":"py-safe-states-update-predecessors","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)\n            for prev in reverse[node]:\n                indegree[prev] -= 1\n                if indegree[prev] == 0:\n                    queue.append(prev)"}]}},{"id":"return-safe-nodes","title":"Return safe nodes in order","description":"Return the collected safe nodes sorted in increasing node id order.","commonMistakes":["Returning the queue order without sorting","Returning unsafe nodes that never reached zero outgoing count"],"hint":"The problem asks for increasing order, but the reverse peel order can be different.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the final sequence of safe node ids in increasing order.","doneWhen":"The function returns the collected safe nodes after sorting or otherwise producing increasing order.","shouldFailWhen":"The code returns a scalar, the original graph, or an unsorted peel-order list when order can differ.","roles":["safe result list","increasing order","returned sequence"],"mustProve":["The returned value is derived from the safe-node result collection.","The result is ordered before return."],"mustNotAccept":["Returning all nodes regardless of safety.","Returning the reverse graph or count array."],"equivalentVariants":["Return sorted(safe).","Collect safe nodes in a boolean array and emit indices in increasing order."],"proofSnippets":[{"id":"py-safe-states-return-safe-nodes","language":"python","code":"class Solution:\n    def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n        n = len(graph)\n        reverse = [[] for _ in range(n)]\n        indegree = [0] * n\n\n        for node in range(n):\n            indegree[node] = len(graph[node])\n            for neighbor in graph[node]:\n                reverse[neighbor].append(node)\n\n        queue = []\n        for node in range(n):\n            if indegree[node] == 0:\n                queue.append(node)\n\n        safe = []\n        head = 0\n        while head < len(queue):\n            node = queue[head]\n            head += 1\n            safe.append(node)\n            for prev in reverse[node]:\n                indegree[prev] -= 1\n                if indegree[prev] == 0:\n                    queue.append(prev)\n\n        return sorted(safe)"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"A node is safe only when every outgoing edge leads to safety; a node that can still reach a cycle never clears.","body":["Reverse the graph and track each node’s outgoing count. Seed the queue with the terminals, then peel: record a node safe and lower the count of everything pointing into it, queuing each node the instant its count hits 0.","The nodes that reach count 0 are safe. The rest can still reach a cycle: the cycle members keep each other’s counts above 0, and any node with a path into them stays blocked too."],"takeaways":[{"title":"Safe means every edge is safe","body":"A node is safe only when its outgoing count reaches 0, so a single edge into a cycle keeps it unsafe no matter how many other edges end well."},{"title":"Peel backward from the dead-ends","body":"Reversing the edges turns terminal nodes into the seeds, so safety spreads back to predecessors in O(n + e) instead of re-walking from every node."},{"title":"Unsafe means it can reach a cycle","body":"Nodes still above count 0 after the queue empties can all reach a cycle: the cycle members block each other, and upstream nodes stay blocked by a path into them, so the recorded set is the full safe answer."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
