{"id":"minimum-number-of-vertices-to-reach-all-nodes","title":"Minimum Number of Vertices to Reach All Nodes","difficulty":"medium","patterns":["topological-sort"],"primaryConcept":"graph-toposort-ordering","concepts":["graph-toposort-ordering"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"edges","sizeMetric":"nodes-plus-edges","secondaryParams":{"n":{"strategy":"scale-with-primary"}},"constraints":["dag"]},"description":"Given a directed acyclic graph with `n` nodes labeled from `0` to `n - 1` and an edge list `edges`, return the smallest set of starting vertices from which every node in the graph is reachable.\n\nThe graph is guaranteed to be a DAG. Return the vertices in increasing order.","examples":[{"input":"n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]","output":"[0,3]","explanation":"Nodes 0 and 3 have no incoming edges; every other node is reachable from one of them."},{"input":"n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]","output":"[0,2,3]","explanation":"The zero-indegree nodes 0, 2, and 3 are all required starting points."}],"constraints":[{"id":"2-n-10-5","text":"2 <= n <= 10^5","check":{"kind":"valueRange","target":"n","selector":"value","min":2,"max":100000}},{"id":"0-len-edges-min-10-5-n-n-1-2","text":"0 <= len(edges) <= min(10^5, n * (n - 1) / 2)"},{"id":"edges-i-length-2","text":"len(edges[i]) == 2","check":{"kind":"shape","target":"edges","shape":"tupleArray","tupleLength":2}},{"id":"0-edges-i-0-edges-i-1-n","text":"0 <= edges[i][0], edges[i][1] < 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":"edges-i-0-edges-i-1","text":"edges[i][0] != edges[i][1]","check":{"kind":"compare","target":"edges","left":{"field":0},"op":"!=","right":{"field":1}}},{"id":"the-graph-is-a-directed-acyclic-graph","text":"The graph is a directed acyclic graph"}],"starterCode":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        # Your code here\n        pass","functionName":"findSmallestSetOfVertices","testCases":[{"id":"1","input":{"n":6,"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]},"expected":[0,3],"description":"Two source components cover all nodes."},{"id":"2","input":{"n":5,"edges":[[0,1],[2,1],[3,1],[1,4],[2,4]]},"expected":[0,2,3],"description":"Three zero-indegree starts are required."},{"id":"3","input":{"n":3,"edges":[]},"expected":[0,1,2],"description":"Without edges every node is a required start."},{"id":"4","input":{"n":4,"edges":[[0,1],[1,2],[2,3]]},"expected":[0],"description":"One chain needs only its source."},{"id":"5","input":{"n":4,"edges":[[1,0],[2,0],[3,0]]},"expected":[1,2,3],"description":"Multiple sources point into one sink."},{"id":"6","input":{"n":2,"edges":[]},"expected":[0,1],"description":"Two isolated nodes both need to be selected."},{"id":"7","input":{"n":6,"edges":[[0,2],[1,2],[1,3],[4,3],[4,5]]},"expected":[0,1,4],"description":"Three disjoint source nodes reach all other nodes."},{"id":"h1","input":{"n":2,"edges":[[1,0]]},"expected":[1],"description":"A two-node graph with one incoming edge needs only its source."},{"id":"h2","input":{"n":5,"edges":[[0,1],[0,2],[2,3]]},"expected":[0,4],"description":"An isolated node still needs to be included as a source."},{"id":"h3","input":{"n":6,"edges":[[0,1],[2,3],[4,5]]},"expected":[0,2,4],"description":"Three disconnected chains require three starts."},{"id":"topup-two-sources","input":{"n":6,"edges":[[0,2],[1,2],[2,3],[4,5]]},"expected":[0,1,4],"description":"Two independent source components must both be selected."},{"id":"topup-chain-single-source","input":{"n":5,"edges":[[0,1],[1,2],[2,3],[3,4]]},"expected":[0],"description":"A single chain needs only its first node."}],"hints":[{"level":1,"content":"A node with an incoming edge can be reached from another node."},{"level":2,"content":"A node with indegree zero cannot be reached from any other node, so it must be included."},{"level":3,"content":"In a DAG, every non-source node is reachable from some source, so all zero-indegree nodes are sufficient."}],"guidedFlow":{"version":2,"progressRevision":"minimum-number-of-vertices-2026-07-19-incoming-evidence-before-indegree","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":"reachability-from-each-node","name":"Repeated reachability searches","summary":"Try DFS or BFS from many starting nodes until all nodes are covered.","decisionReason":"Reachability searches from many starts keep rediscovering nodes that already have an incoming edge from another node. In a DAG, any node with indegree > 0 can be reached from some predecessor, so searching from it is unnecessary.","complexity":{"time":"O(n * (n + e))","space":"O(n + e)"},"tradeoffs":["Runs in O(n * (n + e)) time and uses O(n + e) space."],"isOptimal":false},{"id":"zero-indegree","name":"Collect zero-indegree nodes","summary":"Count incoming edges for every node and return the nodes with indegree zero.","decisionReason":"A node with indegree 0 has no predecessor that could reach it, so it must be included as a start. Every other node has an incoming edge chain back to some zero-indegree node in the DAG.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time and uses O(n + e) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-indegree","title":"Initialize indegree counts","description":"Create an indegree counter for every node.","commonMistakes":["Counting outgoing edges instead of incoming edges","Forgetting nodes with zero incoming edges"],"hint":"Start every node at zero before scanning edges.","semanticSpec":{"intent":"Initialize an indexed incoming-edge count for each node.","doneWhen":"The code creates an indegree array with one entry per node.","shouldFailWhen":"This step should fail if incoming counts are not initialized.","roles":["node index","indegree state"],"mustProve":["The code initializes indegree state over all nodes."],"mustNotAccept":["Using a scalar count for the whole graph.","Counting outgoing edges only."],"equivalentVariants":["Use an array or list initialized to zero."],"proofSnippets":[{"id":"py-min-vertices-init-indegree","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]}},{"id":"populate-edges","title":"Count incoming edges","description":"Scan each directed edge and increment the target node's indegree.","commonMistakes":["Incrementing the source node","Reversing edge direction"],"hint":"For edge source -> target, the target receives one incoming edge.","semanticSpec":{"intent":"Scan directed edges and update each target's incoming-edge count.","doneWhen":"Each edge increments the target indegree.","shouldFailWhen":"This step should fail if the indegree counts are not driven by the edges.","roles":["source node","target node","target indegree"],"mustProve":["The code increments indegree for the edge target."],"mustNotAccept":["Incrementing indegree for the source node.","Ignoring edge direction."],"equivalentVariants":["Destructure each edge or index into each pair."],"proofSnippets":[{"id":"py-min-vertices-populate-edges","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]}},{"id":"collect-sources","title":"Collect zero-indegree nodes","description":"Append every node whose indegree is zero.","commonMistakes":["Collecting nodes with outgoing edges","Returning only the first source"],"hint":"A zero-indegree node cannot be reached from any other node, so it is required.","semanticSpec":{"intent":"Scan all nodes and collect the zero-indegree frontier.","doneWhen":"The code appends each node with indegree zero to the result.","shouldFailWhen":"This step should fail if nonzero-indegree nodes are selected or zero-indegree nodes are skipped.","roles":["node scan","zero indegree","source result"],"mustProve":["The code checks each node's indegree.","The code appends zero-indegree nodes to the output frontier."],"mustNotAccept":["Appending every node unconditionally.","Checking outgoing adjacency length instead of indegree."],"equivalentVariants":["Use a loop or comprehension that filters nodes by indegree zero."],"proofSnippets":[{"id":"py-min-vertices-collect-sources","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        result = []\n        for node in range(n):\n            if in_degree[node] == 0:\n                result.append(node)\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return the source set","description":"Return the collected zero-indegree nodes.","commonMistakes":["Returning the indegree array","Returning adjacency lists"],"hint":"The result list already contains the minimum required starts.","semanticSpec":{"intent":"Return the collected source vertices as the answer.","doneWhen":"The function returns the result sequence after collecting zero-indegree nodes.","shouldFailWhen":"This step should fail if the function returns graph state or degree state.","roles":["source result","final return"],"mustProve":["The code returns the source result sequence."],"mustNotAccept":["Returning the adjacency list.","Returning the indegree array."],"equivalentVariants":["Return the list of zero-indegree node ids."],"proofSnippets":[{"id":"py-min-vertices-return-result","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        result = []\n        for node in range(n):\n            if in_degree[node] == 0:\n                result.append(node)\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}],"slides":[{"id":"read-the-problem","chapter":"The graph","kind":"info","eyebrow":"Read the problem","title":"Find the fewest starts that reach everything","workspacePanel":"problem","body":["You get a directed acyclic graph: n nodes and a list of edges, each edge [a, b] an arrow from a to b. Return the smallest set of nodes you can start from so that following arrows forward reaches every node.","A node with no incoming edge cannot be reached from any other start, so every such node must be chosen. In an acyclic graph, following those sources reaches every remaining node."]},{"id":"naive-reachability","chapter":"The graph","kind":"code-trace","eyebrow":"The obvious way","title":"Search outward from every node and union what each reaches","summary":"It finds a covering set, but it runs a full graph search out of every one of the n nodes. Watch how much it re-walks.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"graph = []\nfor i in range(n):\n    graph.append([])\nfor a, b in edges:\n    graph[a].append(b)\nreaches = []\nfor start in range(n):\n    visited = [False] * n\n    visited[start] = True\n    stack = [start]\n    while stack:\n        node = stack.pop()\n        for nxt in graph[node]:\n            if not visited[nxt]:\n                visited[nxt] = True\n                stack.append(nxt)\n    reaches.append(visited)\n# pick a minimal covering set from the per-start reach sets\nresult = solve_cover(reaches)\nreturn result","typeContext":{"externalFunctions":{"solve_cover":{"params":[{"kind":"list","item":{"kind":"list","item":"bool"}}],"returns":{"kind":"list","item":"int"}}}},"steps":[{"id":"search-from-zero","title":"Run a full search out of node 0","codeLine":8,"summary":"Give node 0 its own fresh visited array, mark 0 itself visited, then walk every arrow forward: 0 covers itself plus 1, 2, and 5 through 2. That is a complete traversal just to learn what one node covers.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":0,"highlighted":[1,2,5],"activeEdges":[[0,1],[0,2],[2,5]]}}},{"id":"search-from-one","title":"Now run another full search out of node 1","codeLine":8,"summary":"Node 1 gets its own fresh visited array too, with 1 marked as covering itself. It has no outgoing arrows, so its search reaches nothing beyond itself, yet the loop still spun up a whole new traversal to find that out, and it will do the same for every remaining node.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":1}}},{"id":"search-from-three","title":"And again out of node 3","codeLine":8,"summary":"Node 3 starts from a clean visited array, marks itself, and reaches 4, then 2, then 5. So 3 covers itself plus 4, 2, and 5. Node 2 and node 5 are walked all over again here, even though node 0's search already covered them. Every start re-walks whatever it can reach.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"},{"id":5,"label":"5"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":3,"highlighted":[4],"activeEdges":[[3,4]]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const graph = [];\nfor (let i = 0; i < n; i++) {\n    graph.push([]);\n}\nfor (const [a, b] of edges) {\n    graph[a].push(b);\n}\nconst reaches = [];\nfor (let start = 0; start < n; start++) {\n    const visited = Array(n).fill(false);\n    visited[start] = true;\n    const stack = [start];\n    while (stack.length > 0) {\n        const node = stack.pop();\n        for (const nxt of graph[node]) {\n            if (!visited[nxt]) {\n                visited[nxt] = true;\n                stack.push(nxt);\n            }\n        }\n    }\n    reaches.push(visited);\n}\n// pick a minimal covering set from the per-start reach sets\nconst result = solveCover(reaches);\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22,"19":25,"20":26},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"16":{"startLine":18,"endLine":21},"17":{"startLine":22,"endLine":24}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const graph: Array<Array<number>> = [];\nfor (let i = 0; i < n; i++) {\n    graph.push([]);\n}\nfor (const [a, b] of edges) {\n    graph[a].push(b);\n}\nconst reaches: Array<Array<boolean>> = [];\nfor (let start = 0; start < n; start++) {\n    const visited = Array(n).fill(false);\n    visited[start] = true;\n    const stack = [start];\n    while (stack.length > 0) {\n        const node = stack.pop()!;\n        for (const nxt of graph[node]) {\n            if (!visited[nxt]) {\n                visited[nxt] = true;\n                stack.push(nxt);\n            }\n        }\n    }\n    reaches.push(visited);\n}\n// pick a minimal covering set from the per-start reach sets\nconst result = solveCover(reaches);\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":16,"15":17,"16":18,"17":22,"19":25,"20":26},"statementBundles":{"3":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"16":{"startLine":18,"endLine":21},"17":{"startLine":22,"endLine":24}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> graph = new ArrayList<>();\nfor (int i = 0; i < n; i++) {\n    graph.add(new ArrayList<>());\n}\nfor (List<Integer> edge : edges) {\n    int a = edge.get(0);\n    int b = edge.get(1);\n    graph.get(a).add(b);\n}\nList<List<Boolean>> reaches = new ArrayList<>();\nfor (int start = 0; start < n; start++) {\n    List<Boolean> visited = new ArrayList<>();\n    for (int index = 0; index < n; index++) {\n        visited.add(false);\n    }\n    visited.set(start, true);\n    List<Integer> stack = new ArrayList<>(List.of(start));\n    while (!stack.isEmpty()) {\n        int node = stack.remove(stack.size() - 1);\n        for (Integer nxt : graph.get(node)) {\n            if (!visited.get(nxt)) {\n                visited.set(nxt, true);\n                stack.add(nxt);\n            }\n        }\n    }\n    reaches.add(visited);\n}\n// pick a minimal covering set from the per-start reach sets\nList<Integer> result = solveCover(reaches);\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":8,"6":10,"7":11,"8":12,"9":16,"10":17,"11":18,"12":19,"13":20,"14":21,"15":22,"16":23,"17":27,"19":30,"20":31},"statementBundles":{"3":{"startLine":3,"endLine":4},"4":{"startLine":5,"endLine":7},"5":{"startLine":8,"endLine":9},"8":{"startLine":12,"endLine":15},"16":{"startLine":23,"endLine":26},"17":{"startLine":27,"endLine":29}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> graph = new();\nfor (int i = 0; i < n; i++) {\n    graph.Add(new List<int>());\n}\nforeach (var item in edges) {\n    int a = item[0];\n    int b = item[1];\n    graph[a].Add(b);\n}\nList<List<bool>> reaches = new();\nfor (int start = 0; start < n; start++) {\n    List<bool> visited = Enumerable.Repeat<bool>(false, n).ToList();\n    visited[start] = true;\n    List<int> stack = new() { start };\n    while (stack.Count > 0) {\n        int node = stack[stack.Count - 1];\n        stack.RemoveAt(stack.Count - 1);\n        foreach (int nxt in graph[node]) {\n            if (!visited[nxt]) {\n                visited[nxt] = true;\n                stack.Add(nxt);\n            }\n        }\n    }\n    reaches.Add(visited);\n}\n// pick a minimal covering set from the per-start reach sets\nList<int> result = SolveCover(reaches);\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":8,"6":10,"7":11,"8":12,"9":13,"10":14,"11":15,"12":16,"13":18,"14":19,"15":20,"16":21,"17":25,"19":28,"20":29},"statementBundles":{"3":{"startLine":3,"endLine":4},"4":{"startLine":5,"endLine":7},"5":{"startLine":8,"endLine":9},"12":{"startLine":16,"endLine":17},"16":{"startLine":21,"endLine":24},"17":{"startLine":25,"endLine":27}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> graph;\nfor (int i = 0; i < n; i++) {\n    graph.push_back(vector<int>{});\n}\nfor (vector<int> item : edges) {\n    int a = item[0];\n    int b = item[1];\n    graph[a].push_back(b);\n}\nvector<vector<bool>> reaches;\nfor (int start = 0; start < n; start++) {\n    vector<bool> visited = vector<bool>(n, false);\n    visited[start] = true;\n    vector<int> stack_{start};\n    while (!stack_.empty()) {\n        int node = stack_.back();\n        stack_.pop_back();\n        for (int nxt : graph[node]) {\n            if (!visited[nxt]) {\n                visited[nxt] = true;\n                stack_.push_back(nxt);\n            }\n        }\n    }\n    reaches.push_back(visited);\n}\n// pick a minimal covering set from the per-start reach sets\nvector<int> result = solve_cover(reaches);\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":8,"6":10,"7":11,"8":12,"9":13,"10":14,"11":15,"12":16,"13":18,"14":19,"15":20,"16":21,"17":25,"19":28,"20":29},"statementBundles":{"3":{"startLine":3,"endLine":4},"4":{"startLine":5,"endLine":7},"5":{"startLine":8,"endLine":9},"12":{"startLine":16,"endLine":17},"16":{"startLine":21,"endLine":24},"17":{"startLine":25,"endLine":27}}}}}},{"id":"naive-cost","chapter":"The graph","kind":"case-probe","eyebrow":"Count the work","title":"How much does searching from every node cost?","summary":"The loop above launched one full search per start. Add up that work across all n starts.","workspacePanel":"trace","options":[{"id":"n-searches","label":"One full traversal per node, so n searches that each walk up to every edge","rationale":"The loop launches a search from all n nodes, and each search can touch every edge, so the total is n times the size of the graph. Nodes like 2 and 5 get re-walked from each start that reaches them.","isCorrect":true},{"id":"one-pass","label":"A single pass over the edges is enough","rationale":"One outward search only tells you what one node reaches. To compare coverage across starts the naive code repeats the search from every node, not once.","isCorrect":false},{"id":"edges-only","label":"It costs only as much as the number of edges","rationale":"Walking the edges once would be O(e), but here the edges are re-walked from each of the n starting nodes, which multiplies the cost by n.","isCorrect":false}],"answer":"It runs a separate traversal from every node, so the cost grows like n times the graph size, re-walking shared descendants over and over. The whole question is whether one node belongs in the answer, and we are paying for full reachability to decide it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-starts-cost","state":{"graph":{"nodes":[{"id":0,"label":"0: walked x1"},{"id":1,"label":"1: walked x2"},{"id":2,"label":"2: walked x4"},{"id":3,"label":"3: walked x1"},{"id":4,"label":"4: walked x2"},{"id":5,"label":"5: walked x5"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"highlighted":[0,1,2,3,4,5],"activeEdges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}}]}},{"id":"edges-as-arrows","chapter":"The idea","kind":"case-probe","eyebrow":"Replace the search","title":"What local evidence proves another node can arrive at node 2?","summary":"The graph shows 0 → 2 and 4 → 2. Nodes 0 and 3 have no arrows pointing into them.","workspacePanel":"visualizer","options":[{"id":"incoming-edge","label":"An edge whose arrow points into node 2","rationale":"An incoming edge gives an immediate one-step route from its source into node 2. Counting incoming arrows records that evidence without launching a traversal.","isCorrect":true},{"id":"outgoing-edge","label":"An edge whose arrow leaves node 2","rationale":"An outgoing edge says where node 2 can go, not whether any other node can arrive at node 2."},{"id":"large-id","label":"A node label larger than 2","rationale":"Numeric labels do not describe reachability. Only the directed edges provide routes between nodes."}],"answer":"An incoming edge is direct evidence that another node can arrive. Count those arrows as indegree: node 2 has indegree 2, while nodes 0 and 3 have indegree 0. Now we can ask what zero incoming evidence forces.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"arrows-intro","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}}]}},{"id":"which-unreachable","chapter":"The idea","kind":"case-probe","eyebrow":"Find the must-haves","title":"Which nodes can no other node ever reach?","summary":"Reaching a node means following some arrow into it.","workspacePanel":"visualizer","options":[{"id":"zero-in","label":"Nodes 0 and 3, the ones with no arrow pointing in","rationale":"Reaching a node means arriving along an arrow that ends at it. With zero arrows in, no path from another node can end at 0 or 3, so each must be a starting point. Nodes with incoming arrows are not forced by this necessity argument; whether the chosen starts cover all of them is the next question.","isCorrect":true},{"id":"leaves","label":"Nodes 1 and 5, the ones with no arrow going out","rationale":"1 and 5 are dead ends, but both have an arrow pointing in, so another node can reach them. Having no way out says nothing about whether something can arrive.","isCorrect":false},{"id":"highest-in","label":"Node 2, since the most arrows point into it","rationale":"Two arrows point into 2, which is exactly why it is easy to reach. The hard-to-reach nodes are the ones with no incoming arrow at all.","isCorrect":false}],"answer":"Nodes 0 and 3. A node is reachable only if some arrow ends at it, so a node with indegree zero can never be arrived at and has to be in the answer.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unreachable-state","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":2,"activeEdges":[[0,2],[4,2]]}}}]}},{"id":"is-it-enough","chapter":"The idea","kind":"case-probe","eyebrow":"Test the claim","title":"Are the indegree-zero nodes alone enough to reach everything?","summary":"Every node with an arrow in was left out of the start set; the question is whether something still reaches it.","workspacePanel":"visualizer","options":[{"id":"dag-yes","label":"Yes: follow any node's incoming arrows backward and you land on a zero-indegree node","rationale":"Pick any node with an arrow in and walk backward along an incoming arrow; that predecessor either has indegree zero or has its own arrow in. The graph is acyclic, so this walk cannot loop and must end at a zero-indegree node, which is in the start set and reaches forward to the node you began at.","isCorrect":true},{"id":"need-more","label":"No: some node deep in the graph still needs its own start","rationale":"Any node you can reach has an incoming arrow, and tracing those arrows back in an acyclic graph always terminates at a zero-indegree node. So no extra start is ever needed beyond the indegree-zero set.","isCorrect":false},{"id":"only-if-connected","label":"Only if the graph is one connected piece","rationale":"Separate pieces are fine: each piece has its own zero-indegree node, and every node in that piece traces back to it. Disconnected components do not break the argument.","isCorrect":false}],"answer":"Yes. Any reachable node has an arrow in, and tracing incoming arrows backward through an acyclic graph cannot loop, so it always ends at a zero-indegree start. The indegree-zero nodes are both necessary and sufficient, so collecting them is the whole answer.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"enough-state","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":5,"highlighted":[2],"activeEdges":[[2,5]]}}}]}},{"id":"sinks-pitfall","chapter":"The idea","kind":"pitfall","eyebrow":"Spot the trap","title":"What if you bump the count on the wrong end of the arrow?","summary":"The plan is right, count indegree and keep the zeros, but it is easy to add the count to edge[0] instead of edge[1]. On the chain 0 to 1 to 2 watch which node ends up at zero.","workspacePanel":"trace","pitfall":"For each edge [a, b] the code does in_degree[a] += 1, charging the source for the arrow, when the arrow actually lands on the target b. The zero-indegree scan is correct; only the increment is on the wrong end.","whyItMatters":"An arrow [a, b] gives an incoming edge to b, not to a. Crediting the source flips the roles: the true source ends up looking reached and the true sink looks like a start. Increment the target, in_degree[b] += 1, so the node nothing points into is the one left at zero.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"in_degree = [0] * n\nfor a, b in edges:\n    in_degree[a] += 1\nresult = []\nfor node in range(n):\n    if in_degree[node] == 0:\n        result.append(node)\nreturn result","steps":[{"id":"count-wrong-end","title":"Charge the source on each edge of the chain 0 to 1 to 2","codeLine":3,"summary":"n = 3, edges = [[0,1],[1,2]]. Edge [0,1] bumps node 0, edge [1,2] bumps node 1, so the counts read 1, 1, 0. The correct answer here is [0], the source of the chain.","state":{"graph":{"nodes":[{"id":0,"label":"0: in 1"},{"id":1,"label":"1: in 1"},{"id":2,"label":"2: in 0"}],"edges":[[0,1],[1,2]]}}},{"id":"pick-wrong-zero","title":"Only node 2 is left at zero, so it is collected","codeLine":7,"summary":"The scan keeps node 2, the dead end, because the miscount left it at zero, and skips 0 and 1. It returns [2].","state":{"graph":{"nodes":[{"id":0,"label":"0: in 1"},{"id":1,"label":"1: in 1"},{"id":2,"label":"2: in 0"}],"edges":[[0,1],[1,2]],"current":2,"visited":[2]}}},{"id":"wrong-cover","title":"Start from node 2 and nothing else is reached","codeLine":8,"summary":"Following arrows out of 2 reaches no one, so [2] covers only itself while 0 and 1 are stranded. The real answer was [0], which reaches all three. Charging in_degree[b] instead would have left 0 at zero.","state":{"graph":{"nodes":[{"id":0,"label":"0: in 1"},{"id":1,"label":"1: in 1"},{"id":2,"label":"2: in 0"}],"edges":[[0,1],[1,2]],"current":2}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const inDegree = Array(n).fill(0);\nfor (const [a, b] of edges) {\n    inDegree[a] = (inDegree[a] + 1);\n}\nconst result = [];\nfor (let node = 0; node < n; node++) {\n    if (inDegree[node] === 0) {\n        result.push(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const inDegree = Array(n).fill(0);\nfor (const [a, b] of edges) {\n    inDegree[a] = (inDegree[a] + 1);\n}\nconst result: Array<number> = [];\nfor (let node = 0; node < n; node++) {\n    if (inDegree[node] === 0) {\n        result.push(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":11},"statementBundles":{"3":{"startLine":3,"endLine":4},"7":{"startLine":8,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] inDegree = new int[n];\nfor (List<Integer> edge : edges) {\n    int a = edge.get(0);\n    int b = edge.get(1);\n    inDegree[a] = (inDegree[a] + 1);\n}\nList<Integer> result = new ArrayList<>();\nfor (int node = 0; node < n; node++) {\n    if (inDegree[node] == 0) {\n        result.add(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":5,"4":7,"5":8,"6":9,"7":10,"8":13},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6},"7":{"startLine":10,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> inDegree = Enumerable.Repeat<int>(0, n).ToList();\nforeach (var item in edges) {\n    int a = item[0];\n    int b = item[1];\n    inDegree[a] = inDegree[a] + 1;\n}\nList<int> result = new();\nfor (int node = 0; node < n; node++) {\n    if (inDegree[node] == 0) {\n        result.Add(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":5,"4":7,"5":8,"6":9,"7":10,"8":13},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6},"7":{"startLine":10,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> in_degree = vector<int>(n, 0);\nfor (vector<int> item : edges) {\n    int a = item[0];\n    int b = item[1];\n    in_degree[a] = (in_degree[a] + 1);\n}\nvector<int> result;\nfor (int node = 0; node < n; node++) {\n    if (in_degree[node] == 0) {\n        result.push_back(node);\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":5,"4":7,"5":8,"6":9,"7":10,"8":13},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6},"7":{"startLine":10,"endLine":12}}}}}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Count arrows in, then keep the zeros","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}}]},"body":["Every count starts at zero. Walk the edge list once, adding one to the indegree of each arrow's target. That gives every node its count of incoming arrows.","Then scan the nodes and keep the ones whose count is still zero. Those are the required starts."]},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the counts","title":"Trace the source set","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-counting","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}},{"id":"keep-zero","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}},{"id":"cover-check","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]],"current":0,"visited":[0,3],"activeEdges":[[0,1],[0,2],[2,5]]}}}]},"beats":[{"id":"after-counting","title":"After counting arrows in, which nodes sit at zero?","summary":"Each edge added one to its target's count.","prompt":"The edge pass is done; read each node's incoming count from its label.","options":[{"id":"zero-and-three","label":"Nodes 0 and 3","rationale":"No edge targets 0 or 3, so both stayed at zero. Every other node was the target of at least one arrow and ticked up.","isCorrect":true},{"id":"just-zero","label":"Only node 0","rationale":"Node 3 is also never an edge target. Edge [3,4] leaves 3 and edge [4,2] never points back, so 3's count is zero too.","isCorrect":false},{"id":"zero-one","label":"Nodes 0 and 1","rationale":"Node 1 is the target of edge [0,1], so its count is 1, not zero. Node 3 is the other untouched node.","isCorrect":false}],"answer":"Nodes 0 and 3 both sit at zero. Nothing pointed into either one, so they are the candidates to keep."},{"id":"keep-zero","title":"Which nodes go into the result?","summary":"The scan keeps a node only when its incoming count is zero.","prompt":"The scan is ready to collect sources from the counts you just read.","options":[{"id":"both","label":"Both 0 and 3","rationale":"Each has indegree zero, so each is unreachable from anywhere else and must be a start. The result is [0, 3].","isCorrect":true},{"id":"smallest","label":"Just 0, the smaller one","rationale":"Both are required. Node 3 is in a separate region that 0 never reaches, so dropping it would strand 3 and 4.","isCorrect":false},{"id":"plus-two","label":"0, 3, and 2 since 2 is shared","rationale":"Node 2 has indegree 2, so it is reached from 0 and from 4. A node with an arrow in is never a required start.","isCorrect":false}],"answer":"Both 0 and 3 go in. They are exactly the indegree-zero nodes, so the result is [0, 3]."},{"id":"cover-check","title":"Does starting from the kept nodes reach all six nodes?","summary":"Follow the arrows out of each chosen start.","prompt":"Start from the nodes you kept and trace the arrows forward.","options":[{"id":"yes-all","label":"Yes: 0 reaches 1, 2, 5 and 3 reaches 4, 2, 5","rationale":"From 0 the arrows reach 1, 2, and 5; from 3 they reach 4, then 2, then 5. Together that is all six nodes, confirming the source set covers everything.","isCorrect":true},{"id":"misses-four","label":"No: node 4 is never reached","rationale":"Node 4 is reached from 3 through edge [3,4]. Since 3 is in the start set, 4 is covered.","isCorrect":false},{"id":"needs-two","label":"Only if 2 is also a start","rationale":"Node 2 is reached from both 0 and 3, so it never needs to be a start itself. The two sources already cover it.","isCorrect":false}],"answer":"Yes. Node 0 reaches 1, 2, and 5; node 3 reaches 4, 2, and 5. All six are covered, so [0, 3] is the answer."}]},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Counting arrows in and keeping the zeros cleared the sample graph. Now set that input aside and look at the thin shapes that stress the rule.","Two thin graphs are worth poking at before you code: one with no edges at all, and one where a node sits off on its own with nothing touching it. Here is the isolated-node shape, a chain 0 to 1 to 2 plus a lone node 3."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1],[1,2]]}}}]}},{"id":"no-edges-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does the rule return when there are no edges?","summary":"n = 3, edges = [].","workspacePanel":"visualizer","options":[{"id":"all-three","label":"Every node, since each has indegree zero","rationale":"No edges means no arrows point into any node, so all three counts stay at zero and all three are required starts. Nothing reaches anything else, so each must be its own start.","isCorrect":true},{"id":"empty","label":"An empty set, since there is nothing to traverse","rationale":"Each isolated node still has to be reached, and the only way to reach it is to start there. Returning nothing would leave every node uncovered.","isCorrect":false},{"id":"just-zero","label":"Only node 0","rationale":"Node 0 cannot reach 1 or 2 with no edges. Each node is its own island, so all three are needed.","isCorrect":false}],"answer":"All three nodes. Every count is zero, so each node is a required start; the source-collecting rule needs no special case for an empty edge list.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-edges-state","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"}],"edges":[]}}}]}},{"id":"isolated-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What about a node that nothing touches?","summary":"n = 5, edges = [[0,1],[0,2],[2,3]], and node 4 stands alone.","workspacePanel":"visualizer","options":[{"id":"zero-and-four","label":"Nodes 0 and 4 are both returned","rationale":"Node 0 has indegree zero and covers the chain 1, 2, 3. Node 4 also has indegree zero, and nothing reaches it, so it must be its own start. The answer is [0, 4].","isCorrect":true},{"id":"just-zero-iso","label":"Only node 0, since it has the edges","rationale":"Node 0 never reaches 4, because no arrow connects them. An isolated node is unreachable from everywhere, so it is still a required start.","isCorrect":false},{"id":"skip-isolated","label":"Node 4 is dropped because it has no outgoing edges","rationale":"Outgoing edges do not decide membership; incoming ones do. Node 4 has indegree zero, so it stays in the answer regardless of where its arrows go.","isCorrect":false}],"answer":"Nodes 0 and 4. Both have indegree zero, and the lone node 4 has no other way to be reached, so collecting all zero-indegree nodes already handles it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"isolated-state","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"},{"id":4,"label":"4: 0"}],"edges":[[0,1],[0,2],[2,3]]}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The one move that matters: a node belongs in the answer exactly when nothing points into it.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":0,"label":"0: 0"},{"id":1,"label":"1: 1"},{"id":2,"label":"2: 2"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 1"},{"id":5,"label":"5: 1"}],"edges":[[0,1],[0,2],[2,5],[3,4],[4,2]]}}}]},"body":["Give every node a count of incoming arrows starting at zero, then walk the edges once, adding one to each arrow's target. Scan the nodes and collect the ones whose count is still zero, and return that list as the source set."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Collect the sources","eyebrow":"Code the rule","summary":"The required starts are the nodes nothing points into. Now build it: give every node a zero count, walk the edges adding one to each arrow's target, collect the nodes still sitting at zero, then return that list.","workspacePanel":"code","checkpoints":[{"id":"init-indegree","title":"Initialize indegree counts","description":"Create an indegree counter for every node.","commonMistakes":["Counting outgoing edges instead of incoming edges","Forgetting nodes with zero incoming edges"],"hint":"Start every node at zero before scanning edges.","semanticSpec":{"intent":"Initialize an indexed incoming-edge count for each node.","doneWhen":"The code creates an indegree array with one entry per node.","shouldFailWhen":"This step should fail if incoming counts are not initialized.","roles":["node index","indegree state"],"mustProve":["The code initializes indegree state over all nodes."],"mustNotAccept":["Using a scalar count for the whole graph.","Counting outgoing edges only."],"equivalentVariants":["Use an array or list initialized to zero."],"proofSnippets":[{"id":"py-min-vertices-init-indegree","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]}},{"id":"populate-edges","title":"Count incoming edges","description":"Scan each directed edge and increment the target node's indegree.","commonMistakes":["Incrementing the source node","Reversing edge direction"],"hint":"For edge source -> target, the target receives one incoming edge.","semanticSpec":{"intent":"Scan directed edges and update each target's incoming-edge count.","doneWhen":"Each edge increments the target indegree.","shouldFailWhen":"This step should fail if the indegree counts are not driven by the edges.","roles":["source node","target node","target indegree"],"mustProve":["The code increments indegree for the edge target."],"mustNotAccept":["Incrementing indegree for the source node.","Ignoring edge direction."],"equivalentVariants":["Destructure each edge or index into each pair."],"proofSnippets":[{"id":"py-min-vertices-populate-edges","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]}},{"id":"collect-sources","title":"Collect zero-indegree nodes","description":"Append every node whose indegree is zero.","commonMistakes":["Collecting nodes with outgoing edges","Returning only the first source"],"hint":"A zero-indegree node cannot be reached from any other node, so it is required.","semanticSpec":{"intent":"Scan all nodes and collect the zero-indegree frontier.","doneWhen":"The code appends each node with indegree zero to the result.","shouldFailWhen":"This step should fail if nonzero-indegree nodes are selected or zero-indegree nodes are skipped.","roles":["node scan","zero indegree","source result"],"mustProve":["The code checks each node's indegree.","The code appends zero-indegree nodes to the output frontier."],"mustNotAccept":["Appending every node unconditionally.","Checking outgoing adjacency length instead of indegree."],"equivalentVariants":["Use a loop or comprehension that filters nodes by indegree zero."],"proofSnippets":[{"id":"py-min-vertices-collect-sources","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        result = []\n        for node in range(n):\n            if in_degree[node] == 0:\n                result.append(node)\n        return []"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return the source set","description":"Return the collected zero-indegree nodes.","commonMistakes":["Returning the indegree array","Returning adjacency lists"],"hint":"The result list already contains the minimum required starts.","semanticSpec":{"intent":"Return the collected source vertices as the answer.","doneWhen":"The function returns the result sequence after collecting zero-indegree nodes.","shouldFailWhen":"This step should fail if the function returns graph state or degree state.","roles":["source result","final return"],"mustProve":["The code returns the source result sequence."],"mustNotAccept":["Returning the adjacency list.","Returning the indegree array."],"equivalentVariants":["Return the list of zero-indegree node ids."],"proofSnippets":[{"id":"py-min-vertices-return-result","language":"python","code":"class Solution:\n    def findSmallestSetOfVertices(self, n: int, edges: list[list[int]]) -> list[int]:\n        in_degree = [0] * n\n        for edge in edges:\n            target = edge[1]\n            in_degree[target] += 1\n        result = []\n        for node in range(n):\n            if in_degree[node] == 0:\n                result.append(node)\n        return result"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"The required starts are exactly the nodes nothing points into; everything else is reachable from one of them.","workspacePanel":"code","body":["Reaching a node means following an arrow into it, so a node with no incoming arrow can never be arrived at and has to be a start. Count incoming arrows once, then keep the nodes that sit at zero.","Because the graph is acyclic, tracing any node's incoming arrows backward always ends at a zero-indegree node, so those sources reach everything and no other start is ever needed."],"takeaways":[{"title":"Indegree zero is unreachable, so it is required","body":"A node with no arrow pointing in cannot be reached from anywhere else, so it must be a starting vertex; that single property picks the whole answer."},{"title":"Sources cover the rest for free","body":"In a DAG every other node traces back along incoming arrows to some zero-indegree node, so the sources alone reach everything and one edge-list pass finds them in O(n + e)."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
