{"id":"graph-valid-tree","title":"Graph Valid Tree","difficulty":"medium","patterns":["union-find"],"primaryConcept":"graph-union-find-connectivity","concepts":["graph-union-find-connectivity","graph-components"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"edges","sizeMetric":"nodes-plus-edges","secondaryParams":{"n":{"strategy":"scale-with-primary"}},"constraints":["mixed-components"]},"executionStyle":"solution-method","compareMode":"exact","description":"Given `n` nodes labeled from `0` to `n - 1` and a list of undirected edges, return `true` if the edges form a valid tree.\n\nAn undirected graph is a tree when it is connected and has no cycles.","examples":[{"input":"n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]","output":"true","explanation":"All nodes are connected and no edge creates a cycle."},{"input":"n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]","output":"false","explanation":"The edge [1,3] closes a cycle."},{"input":"n = 4, edges = [[0,1],[2,3]]","output":"false","explanation":"The graph has two separate components."}],"constraints":[{"id":"1-n-2000","text":"1 <= n <= 2000","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":2000}},{"id":"0-edges-length-5000","text":"0 <= len(edges) <= 5000","check":{"kind":"sizeRange","target":"edges","measure":"arrayLength","min":0,"max":5000}},{"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":"there-are-no-duplicate-undirected-edges","text":"There are no duplicate undirected edges."}],"starterCode":"class Solution:\n    def validTree(self, n: int, edges: list[list[int]]) -> bool:\n        # Your code here\n        pass","functionName":"validTree","testCases":[{"id":"1","input":{"n":5,"edges":[[0,1],[0,2],[0,3],[1,4]]},"expected":true,"description":"Connected acyclic graph."},{"id":"2","input":{"n":5,"edges":[[0,1],[1,2],[2,3],[1,3],[1,4]]},"expected":false,"description":"Cycle exists."},{"id":"3","input":{"n":4,"edges":[[0,1],[2,3]]},"expected":false,"description":"Disconnected graph."},{"id":"4","input":{"n":1,"edges":[]},"expected":true,"description":"Single node tree."},{"id":"5","input":{"n":4,"edges":[[0,1],[1,2],[2,0]]},"expected":false,"description":"Cycle leaves one node disconnected."},{"id":"hidden-1","input":{"n":2,"edges":[[0,1]]},"expected":true,"description":"Two nodes with one edge."},{"id":"hidden-2","input":{"n":4,"edges":[[0,1],[1,2],[2,3],[3,0]]},"expected":false,"description":"Connected graph with one extra cycle edge."},{"id":"hidden-3","input":{"n":6,"edges":[[0,1],[0,2],[0,3],[4,5]]},"expected":false,"description":"Disconnected components."},{"id":"hidden-4","input":{"n":4,"edges":[[0,1],[0,2],[0,3]]},"expected":true,"description":"A star-shaped graph is still a tree."},{"id":"hidden-5","input":{"n":4,"edges":[[0,1],[1,2],[2,3],[0,2]]},"expected":false,"description":"An extra edge creates a cycle without using a self-loop."},{"id":"topup-1","input":{"n":5,"edges":[[0,1],[1,2],[2,3]]},"expected":false,"description":"Top-up case 1: having n - 2 edges guarantees at least one disconnected node."},{"id":"topup-2","input":{"n":6,"edges":[[0,1],[1,2],[1,3],[3,4],[4,5]]},"expected":true,"description":"Top-up case 2: a connected branching graph with exactly n - 1 edges is a tree."},{"id":"cycle-leaves-node-out","input":{"n":5,"edges":[[1,3],[4,0],[3,4],[3,0]]},"expected":false,"description":"There are n - 1 edges, yet nodes 0, 3 and 4 form a cycle and node 2 has no edge."},{"id":"cycle-cuts-off-two-nodes","input":{"n":7,"edges":[[3,5],[4,2],[3,2],[1,3],[2,5],[6,0]]},"expected":false,"description":"There are n - 1 edges, yet nodes 2, 3 and 5 form a cycle and nodes 0 and 6 are cut off from the rest."}],"hints":[{"level":1,"content":"A tree with n nodes must have exactly n - 1 edges."},{"level":2,"content":"Use union-find to merge each edge and reject an edge whose endpoints already share a root.","revealPattern":true},{"level":3,"content":"After the edge-count check, no cycle during all unions is enough to prove the graph is connected and acyclic."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"How should the function test both tree requirements?","decisionPrompt":"Compare what each approach has to store and how much work it does for each edge.","approaches":[{"id":"union-find-edge-count","name":"Edge count, then union-find","summary":"Return false unless there are n - 1 edges, then merge the two ends of every edge and return false if two ends already share a root.","decisionReason":"With exactly n - 1 edges, every edge has to join two different groups. Parent pointers answer that for each edge as it is read, using two arrays of length n.","complexity":{"time":"O(n α(n))","space":"O(n)"},"tradeoffs":["Each edge is handled once as it is read, and the only storage is the parent and rank arrays."],"isOptimal":true},{"id":"build-adjacency-dfs","name":"Edge count, then a traversal","summary":"Return false unless there are n - 1 edges, build a neighbor list for every node, and walk the graph from node 0 to see whether all n nodes are reached.","decisionReason":"This also works: with n - 1 edges, reaching all n nodes from node 0 rules out a cycle as well. It has to build a neighbor list for every node before the walk can start, where union-find handles each edge as it is read.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["The neighbor lists have to be built before the walk can start."],"isOptimal":false,"isViable":true}]},"codingCheckpoints":[{"id":"edge-count","title":"Check the edge count first","description":"Return false unless the number of edges is exactly one less than the number of nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"guards_relation_count_matches_element_count_minus_one","scope":"edge-count","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the number of edges with n, which rejects every real tree","Rejecting only an empty edge list, which lets every other wrong count through"],"hint":"A tree on n nodes has n - 1 edges, so any other count settles the answer before a single edge is read.","semanticSpec":{"intent":"Prove the relation count is checked against the element count minus one.","doneWhen":"The solution rejects an edge list whose length is not n - 1.","shouldFailWhen":"The code does not compare the edge count with the node-count minus-one bound.","roles":["relation sequence","element count","early rejection"],"mustProve":["The relation sequence length is read.","The count bound is the element count minus one.","A mismatch returns false."],"mustNotAccept":["Comparing the edge count with n.","Checking only whether edges is empty."],"equivalentVariants":["Use != and return false from the mismatch branch.","Use == and return false from the failed-equality branch."],"proofSnippets":[{"id":"py-valid-tree-edge-count","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        return True"}]}},{"id":"init-arrays","title":"Set up parent and rank","description":"Give every node itself as its parent and a rank of 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"initializes_parent_and_rank_state","scope":"init-arrays","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Starting every parent at 0, which puts all the nodes in one group before any edge is read","Giving rank a different length from parent"],"hint":"Before any edge is read there are n groups of one, so every node is its own root and no tree has any height yet.","semanticSpec":{"intent":"Initialize aligned parent and rank state for all n nodes.","doneWhen":"Parent has one self-representative entry per node and rank has one zero seed per node.","shouldFailWhen":"Parent or rank is missing, empty, or sized independently from the node count.","roles":["parent state","rank state","node count"],"mustProve":["Parent is seeded from the node range.","Rank is aligned with parent."],"mustNotAccept":["An empty parent list.","A rank list with a mismatched size."],"equivalentVariants":["Use arrays or lists for parent and rank.","Fill parent with each node's own index."],"proofSnippets":[{"id":"py-valid-tree-init-parent-rank","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n"}]}},{"id":"find-function","title":"Write find with the shortcut","description":"Follow parent pointers from a node up to its root, point the node straight at that root, and return the root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning the node's parent, which is one step up and may not be the root","Finding the root but never storing it, so every call repeats the whole walk"],"hint":"A root is the node that is its own parent. Once the walk has reached it, storing it as the starting node's parent makes the next walk from that node a single step.","semanticSpec":{"intent":"Resolve representatives through parent links and compress each visited node to its root.","doneWhen":"find returns parent[x] after recursively rewriting parent[x] to the root when needed.","shouldFailWhen":"find only reads parent[x] and never writes compressed representatives.","roles":["find helper","parent state","representative"],"mustProve":["find follows parent links until a root.","find writes the resolved root back to the queried node."],"mustNotAccept":["A non-compressing parent lookup.","A helper that ignores the parent state."],"equivalentVariants":["Use recursive path compression.","Use iterative compression with a final root writeback."],"proofSnippets":[{"id":"py-valid-tree-path-compression","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]"}]}},{"id":"union-function","title":"Link one root under the other","description":"In union, find the root of each end of the edge and make one root the parent of the other.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Pointing one end of the edge at the other end without finding their roots","Finding the root of only one end"],"hint":"The pointer to rewrite belongs to a root. Pointing a node from the middle of one group at the other group leaves the nodes above it behind.","semanticSpec":{"intent":"Merge sets by linking representatives rather than raw nodes.","doneWhen":"union finds both roots and writes a parent link between representatives.","shouldFailWhen":"union links raw node ids or never calls find on both endpoints.","roles":["union helper","find helper","representative roots","parent state"],"mustProve":["Both inputs are resolved through find.","Only representatives are linked."],"mustNotAccept":["Raw parent writes without representative lookup.","Merging based on the original endpoints."],"equivalentVariants":["Return a boolean when a merge happens.","Return nothing from a helper used only for merging."],"proofSnippets":[{"id":"py-valid-tree-union-by-root","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            parent[root_y] = root_x"}]}},{"id":"union-by-rank","title":"Let rank decide which root goes under","description":"Put the root with the lower rank under the root with the higher rank. When the ranks tie, pick either one and add 1 to the rank of the root that stays on top.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-by-rank","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the ranks but making the same link in every case","Adding 1 to a rank when the two ranks were different"],"hint":"Rank limits how tall a tree can be. A lower tree fits under a higher one without changing that limit, and two trees with the same limit can produce one that is a step taller.","semanticSpec":{"intent":"Keep union-find trees shallow by using rank-guided representative writes.","doneWhen":"The lower-rank root attaches to the higher-rank root, and a tie increments the chosen root's rank.","shouldFailWhen":"Rank is read but parent writes ignore the rank branches or ties never update rank.","roles":["rank state","representative roots","parent state"],"mustProve":["Rank comparison controls parent writes.","Tie handling increments rank."],"mustNotAccept":["Rank comparisons with no writeback.","Incrementing rank in the wrong branch."],"equivalentVariants":["Attach root_y to root_x on ties.","Attach root_x to root_y on ties if the rank increment matches."],"proofSnippets":[{"id":"py-valid-tree-ranked-union","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1"}]}},{"id":"union-success-return","title":"Report a merge from union","description":"After union has linked two different roots, have it return true.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_successful_merge_boolean","scope":"union-success-return","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning nothing after the link, so the caller cannot tell a merge from a failure"],"hint":"The loop over the edges needs to know whether each edge joined two groups. Reaching the link means this one did.","semanticSpec":{"intent":"Finish the merge helper's boolean contract for the successful merge case.","doneWhen":"The union helper returns true after linking two different representatives.","shouldFailWhen":"The successful merge path returns a non-true value or falls through without a boolean success return.","roles":["union helper","representative link","successful merge"],"mustProve":["Representatives are linked.","The successful merge path returns true."],"mustNotAccept":["Returning false after the parent write.","Returning an empty collection after the parent write."],"equivalentVariants":["Use `return True` after the parent/rank branches complete.","Return true from each successful rank branch."],"proofSnippets":[{"id":"py-valid-tree-union-success-return","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True"}]}},{"id":"check-cycle","title":"Report false when the roots match","description":"In union, before linking anything, return false if both ends of the edge have the same root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"detects_existing_connection_by_find","scope":"check-cycle","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the two ends of the edge themselves, which only catches an edge from a node to itself","Linking first and looking up the two roots afterward, when they always match"],"hint":"Two nodes with the same root are already connected, so one more edge between them closes a cycle.","semanticSpec":{"intent":"Use representative equality to reject cycle-forming edges.","doneWhen":"The merge helper returns false when both endpoints resolve to the same root.","shouldFailWhen":"The code compares raw endpoints or ignores a failed merge.","roles":["find helper","representative roots","cycle rejection"],"mustProve":["Both endpoints are resolved to representatives.","A same-root comparison returns false."],"mustNotAccept":["Comparing x == y before find.","Skipping the equality guard."],"equivalentVariants":["Return false from union on a same-root edge.","Reject the edge in the loop after comparing representatives."],"proofSnippets":[{"id":"py-valid-tree-cycle-guard","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True"}]}},{"id":"process-edges","title":"Send every edge through union","description":"Loop over the edges, call union with the two ends of each one, and return false as soon as union reports false.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"processes_edges_until_cycle","scope":"process-edges-boolean-reject","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Calling union but ignoring what it reports","Stopping after the first edge"],"hint":"With n - 1 edges there is none to spare, so the first edge that fails to merge already means the graph is not a tree.","semanticSpec":{"intent":"Apply the union helper to every pair in the edge sequence.","doneWhen":"The code loops over edges, calls union with the current edge endpoints, and returns false for a failed merge.","shouldFailWhen":"The edge loop is missing or union is called with constants.","roles":["edge list","edge endpoints","union helper"],"mustProve":["The edge sequence is scanned.","Each scanned pair is passed to union.","A failed merge returns false."],"mustNotAccept":["Calling union once outside a loop.","Using fixed endpoints inside the loop.","Ignoring a failed union result."],"equivalentVariants":["Loop with tuple unpacking.","Loop over edges and index edge[0], edge[1]."],"proofSnippets":[{"id":"py-valid-tree-process-edges","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True\n        for u, v in edges:\n            if not union(u, v):\n                return False"}]}},{"id":"return-success","title":"Return true after the loop","description":"If the loop ends without any edge failing, return true.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_successful_merge_boolean","scope":"return-success","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning false after the loop, which rejects every tree"],"hint":"n - 1 edges that each merged two groups leave exactly one group, and none of them closed a cycle.","semanticSpec":{"intent":"Return the successful tree verdict after the edge scan completes.","doneWhen":"This step is done when the completed merge scan returns true.","shouldFailWhen":"This step should fail if the function returns a non-true value after all merges succeed.","roles":["edge scan","successful verdict"],"mustProve":["The edge sequence is scanned.","The completed edge pass returns true."],"mustNotAccept":["Returning false after the loop.","Returning an empty array or falling off the end."],"equivalentVariants":["Use `return True` after the edge loop.","Use an equivalent boolean true return after all merge checks pass."],"proofSnippets":[{"id":"py-valid-tree-return-success","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True\n        for u, v in edges:\n            if not union(u, v):\n                return False\n        return True"}]}}],"slides":[{"id":"read-the-signal","kind":"info","title":"Do these nodes and edges form a tree?","workspacePanel":"problem","body":["You are given a number of nodes, labeled from 0 upward, and a list of edges. Each edge is a pair of nodes with a connection between them. The connection has no direction, so the arrowheads in the drawing only show which node a pair lists first.","Return true if the nodes and edges form a tree, and false if they do not. A tree needs two things at once. Every node can be reached from every other node, and there is no cycle. A cycle is a route that leaves a node and comes back to it without using an edge twice.","The drawing has five nodes and four edges. Every node can be reached and nothing loops, so this input returns true."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3],[1,3],[4,3]]}}}]}},{"id":"extra-edge-cycle","kind":"case-probe","title":"One more edge joins 0 and 2. Is this still a tree?","workspacePanel":"visualizer","options":[{"id":"cycle","label":"No, because 0, 1, 3 and 2 now form a cycle","rationale":"Walk from 0 to 1 to 3 to 2, and the new edge brings you back to 0. Every node can still be reached, but a tree cannot contain a cycle.","isCorrect":true},{"id":"still-reachable","label":"Yes, because every node can still reach every other","rationale":"Reaching every node is one of the two requirements. The other one fails: the route 0, 1, 3, 2, 0 is a cycle.","isCorrect":false},{"id":"cut-off","label":"No, because node 4 can no longer be reached","rationale":"Node 4 is still joined to node 3, so nothing was cut off. What the new edge added is the cycle 0, 1, 3, 2, 0.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"five-edges","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3],[1,3],[4,3],[0,2]],"current":0,"highlighted":[2],"activeEdges":[[0,2]]}}}]}},{"id":"missing-edge-cut-off","kind":"case-probe","title":"Back to the original four edges, minus the one between 4 and 3. Is this a tree?","workspacePanel":"visualizer","options":[{"id":"unreachable","label":"No, because node 4 cannot be reached from the others","rationale":"There is no cycle anywhere in this drawing. Node 4 has no edge at all, though, and a tree has to connect every node.","isCorrect":true},{"id":"no-cycle","label":"Yes, because there is no cycle","rationale":"Having no cycle is one of the two requirements. The other one fails: no route leads to node 4.","isCorrect":false},{"id":"four-of-five","label":"Yes, because 0, 1, 2 and 3 form a tree","rationale":"Those four nodes do form a tree among themselves. The input has five nodes, and all five have to be connected.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-edges","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3],[1,3]]}}}]}},{"id":"count-the-groups","kind":"info","title":"Count the groups as the edges go in","workspacePanel":"visualizer","body":["Take all the edges away, then put the original four back one at a time. After each one, count the groups: sets of nodes joined to each other, directly or through other nodes."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-edges","title":"No edges yet","summary":"Each of the five nodes is a group of one, so there are five groups.","state":{"groups":5,"graph":{"nodes":[0,1,2,3,4],"edges":[]}}},{"id":"add-0-1","title":"Edge [0,1] joins two groups","summary":"0 and 1 were each alone, and now they are one group. Five groups have become four.","state":{"groups":4,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]}}},{"id":"add-2-3","title":"Edge [2,3] joins two more","summary":"2 and 3 were each alone as well. Four groups have become three: {0,1}, {2,3} and {4}.","state":{"groups":3,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3]],"current":2,"highlighted":[3],"activeEdges":[[2,3]]}}}]}},{"id":"edges-to-one-group","kind":"case-probe","title":"Three groups are left. How many more edges does it take to make them one group?","workspacePanel":"visualizer","options":[{"id":"two","label":"Two, each joining two different groups","rationale":"An edge that joins two different groups leaves one group fewer, so three groups go to two and then to one. In the original drawing those two edges are [1,3] and [4,3]. All four of its edges joined two different groups.","isCorrect":true},{"id":"one","label":"One, if it is placed well","rationale":"An edge has only two ends, so it can join at most two groups. With three groups, one edge always leaves at least two.","isCorrect":false},{"id":"three","label":"Three, one for each group","rationale":"Each joining edge removes exactly one group. Going from three groups to one means removing two, which takes two edges.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-groups","state":{"groups":3,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3]]}}}]}},{"id":"edge-count","kind":"case-probe","title":"Five nodes took four edges. How many edges does a tree on n nodes have?","workspacePanel":"visualizer","options":[{"id":"n-minus-1","label":"Exactly n - 1","rationale":"n separate nodes are n groups, and each joining edge removes one group. Getting down to a single group takes n - 1 of them. So the function can start with a count check: any number of edges other than n - 1 returns false.","isCorrect":true},{"id":"n","label":"Exactly n","rationale":"At most n - 1 edges can each join two groups, because by then one group is left. With n edges, at least one has both ends in the same group, and that edge closes a cycle, as the edge between 0 and 2 did.","isCorrect":false},{"id":"depends","label":"It depends on the shape","rationale":"A chain, a star and every shape in between start from n groups and end with one. Each needs the same n - 1 joining edges.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"four-edges","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3],[1,3],[4,3]]}}}]}},{"id":"right-count-wrong-shape","kind":"case-probe","title":"Suppose the four edges are these instead, so the count is still n - 1. Is this a tree?","workspacePanel":"visualizer","options":[{"id":"cycle-and-cut-off","label":"No, it has a cycle and node 4 is cut off","rationale":"0, 1, 3 and 2 form a cycle, and no edge reaches node 4. The count is right and both requirements still fail. So passing the count check is not enough, and the edges still have to be checked one by one.","isCorrect":true},{"id":"count-is-enough","label":"Yes, n - 1 edges always form a tree","rationale":"Every tree has n - 1 edges, but the reverse does not follow. Here the four edges form the cycle 0, 1, 3, 2, 0 and leave node 4 out.","isCorrect":false},{"id":"only-cut-off","label":"No, but only because node 4 is cut off","rationale":"Node 4 is cut off, and there is a second problem: the route 0, 1, 3, 2, 0 is a cycle.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"right-count","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[1,3],[2,3],[0,2]]}}}]}},{"id":"count-collapse","kind":"case-probe","title":"With only the first three of those edges, the groups are {0,1,2,3} and {4}. Which fourth edge makes a tree?","workspacePanel":"visualizer","options":[{"id":"reach-4","label":"Any edge with one end at node 4","rationale":"It joins the last two groups into one, and node 4 had no route to the others, so no cycle forms. With n - 1 edges there is none to spare: one edge inside a group would close a cycle and leave a node out.","isCorrect":true},{"id":"unjoined-pair","label":"The edge [0,2], since 0 and 2 have no edge between them yet","rationale":"0 and 2 are already in the same group, connected through 1 and 3. A second route between them is a cycle, and node 4 stays outside.","isCorrect":false},{"id":"any-edge","label":"Any edge at all, since four edges is the right count","rationale":"The count only says how many edges there are. An edge with both ends inside {0,1,2,3} closes a cycle and leaves node 4 outside.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-of-four","state":{"groups":2,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[1,3],[2,3]]}}}]}},{"id":"groups-in-code","kind":"info","title":"With n - 1 edges, every edge has to join two different groups","workspacePanel":"visualizer","body":["So for each edge the function asks one question: are these two nodes already in the same group? If they are not, it merges their two groups.","The function sees only pairs of numbers, like the ones drawn here. Both steps have to work from those, and stay cheap when there are thousands of nodes."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pairs-only","state":{"n":5,"grid":[[0,1],[2,3],[1,3],[4,3]],"labels":{"grid":"edges"}}}]}},{"id":"point-to-rep","kind":"info","title":"Each node points at one other node, or at itself","workspacePanel":"visualizer","body":["Keep one number for each node in an array called `parent`: the node it points to. A node that points to itself is a root, and every group has exactly one root."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-roots","title":"All five nodes start as roots","summary":"parent[x] = x for all five nodes, so there are five groups of one.","state":{"graph":{"parent":[0,1,2,3,4]},"rows":[{"label":"parent","values":[0,1,2,3,4]}]}},{"id":"link-0-1","title":"Edge [0,1]: point 1 at 0","summary":"parent[1] = 0. Node 0 still points to itself, so it is the root of the group {0,1}.","state":{"graph":{"parent":[0,0,2,3,4],"current":1,"highlighted":[0],"activeEdges":[[1,0]]},"rows":[{"label":"parent","values":[0,0,2,3,4],"changed":[1]}]}},{"id":"link-2-3","title":"Edge [2,3]: point 3 at 2","summary":"parent[3] = 2, which makes 2 the root of {2,3}. Node 4 is still alone.","state":{"graph":{"parent":[0,0,2,2,4],"current":3,"highlighted":[2],"activeEdges":[[3,2]]},"rows":[{"label":"parent","values":[0,0,2,2,4],"changed":[3]}]}}]}},{"id":"link-roots","kind":"case-probe","title":"Edge [1,3] has to merge {0,1} and {2,3}. Which single change to parent does it?","workspacePanel":"visualizer","options":[{"id":"root-under-root","label":"parent[2] = 0","rationale":"2 is the root of its group, so everything that pointed to 2 now leads on to 0, and all four nodes end at the same root. Neither end of the edge changed: a merge always links one root under the other.","isCorrect":true},{"id":"end-to-end","label":"parent[3] = 1","rationale":"3 stops pointing at 2 and joins 0 and 1. Node 2 still points to itself, so it is left behind in a group of its own even though the edge [2,3] exists.","isCorrect":false},{"id":"other-end","label":"parent[1] = 3","rationale":"1 stops pointing at 0 and joins 2 and 3. Node 0 still points to itself, so it is left behind even though the edge [0,1] exists.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-1-3","state":{"graph":{"parent":[0,0,2,2,4],"current":1,"highlighted":[3]},"rows":[{"label":"parent","values":[0,0,2,2,4]}]}}]}},{"id":"same-group-invariant","kind":"case-probe","title":"parent[2] is now 0. How can code tell that 1 and 3 are in the same group?","workspacePanel":"visualizer","options":[{"id":"same-root","label":"Follow parent up from each node and compare where the two walks stop","rationale":"1 goes to 0, and 3 goes to 2 and then to 0. Two nodes are in the same group exactly when their walks end at the same root. This walk is a helper called find: find(x) follows parent from x to the node that points to itself, and returns it.","isCorrect":true},{"id":"same-parent","label":"Compare the two entries parent[1] and parent[3]","rationale":"parent[1] is 0 and parent[3] is 2. They differ, yet both nodes are in the group {0,1,2,3}: one step up does not always reach the root.","isCorrect":false},{"id":"direct-parent","label":"Check whether one of them is the parent of the other","rationale":"Neither points at the other: 1 points to 0 and 3 points to 2. Nodes can share a group without any pointer between them.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-1-3","state":{"graph":{"parent":[0,0,0,2,4],"current":1,"highlighted":[3]},"rows":[{"label":"parent","values":[0,0,0,2,4]}]}}]}},{"id":"shorten-the-walk","kind":"case-probe","title":"find(3) walks 3 to 2 to 0 before it reaches the root. What can it write so that the next find(3) takes one step?","workspacePanel":"visualizer","options":[{"id":"point-at-root","label":"parent[3] = 0","rationale":"3 now points straight at its root and stays in the same group, so the next find(3) takes one step. find can do this for every node it passes on the way up. That is called path compression.","isCorrect":true},{"id":"point-root-down","label":"parent[0] = 3","rationale":"0 would stop being a root, and the pointers would run from 0 to 3 to 2 and back to 0. A walk up from any of them would never end.","isCorrect":false},{"id":"leave-it","label":"Nothing, the pointers have to stay as the merges left them","rationale":"The pointers only have to preserve which root each node reaches. Pointing 3 at 0 keeps that and saves a step on the next call.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walk-from-3","state":{"graph":{"parent":[0,0,0,2,4],"current":3,"highlighted":[2,0]},"rows":[{"label":"parent","values":[0,0,0,2,4]}]}}]}},{"id":"smaller-under-larger","kind":"case-probe","title":"The last edge is [4,3]. find(4) is 4 and find(3) is 0. Which change keeps the walks to the root shortest?","workspacePanel":"visualizer","options":[{"id":"four-under-zero","label":"parent[4] = 0","rationale":"Node 4 ends up one step from the root, and no other node moves. That was the fourth merge, so one group is left and the original input returns true.","isCorrect":true},{"id":"zero-under-four","label":"parent[0] = 4","rationale":"Nodes 0, 1, 2 and 3 would each be one step farther from the root, all to save a single step for node 4.","isCorrect":false},{"id":"no-difference","label":"Either one, the walks come out the same","rationale":"Both changes give one group, so the result is the same either way. The walks differ: under root 4, four nodes move a step farther, and under root 0 only node 4 does.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"before-4-3","state":{"graph":{"parent":[0,0,0,0,4],"current":4,"highlighted":[3]},"rows":[{"label":"parent","values":[0,0,0,0,4]}]}}]}},{"id":"rank-number","kind":"info","title":"Each root keeps a number for the height of its tree","workspacePanel":"visualizer","body":["At edge [4,3] the drawing showed which tree was bigger. The function sees only arrays, so it keeps a second one, `rank`. For a root, rank is an upper limit on the number of steps in the longest walk up to it.","Every node starts at rank 0. When two roots merge, the one with the lower rank goes under the other.","Go back to edge [1,3], before it merged anything. Roots 0 and 2 each had one node a single step below them, so each had rank 1."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ranks-before-1-3","state":{"graph":{"parent":[0,0,2,2,4]},"rows":[{"label":"parent","values":[0,0,2,2,4]},{"label":"rank","values":[1,0,1,0,0]}]}}]}},{"id":"rank-tie","kind":"case-probe","title":"Edge [1,3] merges roots 0 and 2, both rank 1, and 2 goes under 0. What should rank[0] be afterward?","workspacePanel":"visualizer","options":[{"id":"two","label":"2","rationale":"The longest walk is now 3 to 2 to 0, which is two steps. Two trees of the same rank can produce one that is a step taller, so the limit has to rise by 1.","isCorrect":true},{"id":"one","label":"1","rationale":"Rank 1 allows walks of one step, and 3 is now two steps from root 0. The number would be too low.","isCorrect":false},{"id":"three","label":"3","rationale":"Three nodes now sit below 0, but rank limits the longest walk, and that walk is two steps: 3 to 2 to 0.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"tie-at-1-3","state":{"graph":{"parent":[0,0,2,2,4],"current":0,"highlighted":[2]},"rows":[{"label":"parent","values":[0,0,2,2,4]},{"label":"rank","values":[1,0,1,0,0]}]}}]}},{"id":"dry-run-setup","kind":"info","title":"The whole function runs on the input that had the right count and the wrong shape.","workspacePanel":"visualizer","body":["n is 5 and there are four edges, so the count check passes. Every node starts as its own root with rank 0.","Each edge goes to a helper called union, which runs find on both ends and reports whether it merged two groups. On a tie, this run puts the second root under the first."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"input","state":{"n":5,"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[1,3],[2,3],[0,2]]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Run the four edges through union","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start","state":{"graph":{"parent":[0,1,2,3,4]},"rows":[{"label":"parent","values":[0,1,2,3,4]},{"label":"rank","values":[0,0,0,0,0]}]}},{"id":"after-0-1","state":{"graph":{"parent":[0,0,2,3,4],"current":1,"highlighted":[3]},"rows":[{"label":"parent","values":[0,0,2,3,4],"changed":[1]},{"label":"rank","values":[1,0,0,0,0],"changed":[0]}]}},{"id":"after-1-3","state":{"graph":{"parent":[0,0,2,0,4],"current":2,"highlighted":[3]},"rows":[{"label":"parent","values":[0,0,2,0,4],"changed":[3]},{"label":"rank","values":[1,0,0,0,0]}]}},{"id":"after-2-3","state":{"graph":{"parent":[0,0,0,0,4],"current":0,"highlighted":[2]},"rows":[{"label":"parent","values":[0,0,0,0,4],"changed":[2]},{"label":"rank","values":[1,0,0,0,0]}]}},{"id":"after-0-2","state":{"graph":{"parent":[0,0,0,0,4],"current":0,"highlighted":[2]},"rows":[{"label":"parent","values":[0,0,0,0,4]},{"label":"rank","values":[1,0,0,0,0]}],"returns":false}}]},"beats":[{"id":"edge-0-1","title":"The first edge is [0,1]. What does union write?","summary":"","prompt":"","options":[{"id":"link-and-rank","label":"parent[1] = 0, and rank[0] becomes 1","rationale":"The roots differ, so they merge. The ranks tie, so the second root goes under the first and the first root's rank rises by 1.","isCorrect":true},{"id":"link-only","label":"parent[1] = 0, and no rank changes","rationale":"The link is right, but both roots had rank 0. A tie can make the tree a step taller, so rank[0] has to become 1.","isCorrect":false},{"id":"report-false","label":"Nothing, and it reports false","rationale":"union reports false only when both ends have the same root. Here the roots are 0 and 1.","isCorrect":false}]},{"id":"edge-1-3","title":"Next is [1,3]. What does union write this time?","summary":"","prompt":"","options":[{"id":"three-under-zero","label":"parent[3] = 0, and no rank changes","rationale":"find(1) is 0, with rank 1, and find(3) is 3, with rank 0. The lower rank goes under the higher, and the tree under 0 was already one step tall, so its rank stays 1.","isCorrect":true},{"id":"rank-up","label":"parent[3] = 0, and rank[0] becomes 2","rationale":"Rank rises only on a tie, and these ranks are 1 and 0. Node 3 sits one step below 0, the same distance as node 1, so the limit of 1 still holds.","isCorrect":false},{"id":"zero-under-three","label":"parent[0] = 3, and rank[3] becomes 1","rationale":"Root 0 has rank 1 and root 3 has rank 0, and the lower rank goes under the higher. Putting 0 under 3 would move 0 and 1 a step farther from the root.","isCorrect":false}]},{"id":"edge-2-3","title":"Edge [2,3] lists 2 first. Which change does union make?","summary":"","prompt":"","options":[{"id":"two-under-zero","label":"parent[2] = 0","rationale":"find(2) is 2, with rank 0, and find(3) is 0, with rank 1. Root 2 has the lower rank, so it goes under root 0. Being listed first in the edge makes no difference.","isCorrect":true},{"id":"zero-under-two","label":"parent[0] = 2","rationale":"That puts the higher-rank root underneath. Nodes 0, 1 and 3 would each move a step farther from the root.","isCorrect":false},{"id":"end-to-end","label":"parent[3] = 2","rationale":"Node 3 is not a root. Rewriting its pointer pulls it out from under 0, and nodes 0 and 1 are left in a separate group.","isCorrect":false}]},{"id":"edge-0-2","title":"The last edge is [0,2]. What does union report?","summary":"","prompt":"","options":[{"id":"false","label":"false, and the function returns false","rationale":"find(0) and find(2) are both 0. The same root means 0 and 2 were already connected, so this edge closes a cycle. Only three of the four edges merged, which is why node 4 is still alone.","isCorrect":true},{"id":"true-after-write","label":"true, after writing parent[2] = 0 again","rationale":"Nodes that already share a root need no link, and reporting true would hide the cycle 0, 1, 3, 2, 0.","isCorrect":false},{"id":"true-no-write","label":"true, without writing anything","rationale":"Nothing changes, and that failed merge is the signal. Reporting true would accept a graph with a cycle and an unconnected node.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The run caught the cycle at [0,2]. Next, two more inputs.","workspacePanel":"visualizer","body":["The first is a single node with no edges. The second has four nodes and only the edges [0,1] and [2,3].","Do the count check and union still give the right answer on both?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-node","state":{"n":1,"graph":{"nodes":[0],"edges":[]}}}]}},{"id":"single-node-edge","kind":"case-probe","title":"In the first input, n is 1 and there are no edges. What does the function return?","workspacePanel":"visualizer","options":[{"id":"true","label":"true: the count check passes and no edge can fail","rationale":"Zero edges equals n - 1 when n is 1. The loop over the edges never runs, so nothing reports false, and one node alone is already one connected group.","isCorrect":true},{"id":"false-count","label":"false: an empty edge list fails the count check","rationale":"The count check compares the number of edges with n - 1. Here that is 0 against 0, which passes.","isCorrect":false},{"id":"false-no-merge","label":"false: with no edges, nothing was ever merged","rationale":"Merges are only needed to bring separate groups together. One node is a single group from the start, with nothing left to connect.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-node","state":{"n":1,"graph":{"nodes":[0],"edges":[]}}}]}},{"id":"two-pairs-edge","kind":"case-probe","title":"In the second, n is 4 and the edges are [0,1] and [2,3]. What does the function return, and where is that decided?","workspacePanel":"visualizer","options":[{"id":"count-check","label":"false, at the count check","rationale":"Two edges is not n - 1 = 3, so the function returns false before it reads a single edge. Two edges can bring four groups down to two at best. The merges alone would accept this input, just as the count alone accepted the one with a cycle.","isCorrect":true},{"id":"union-fails","label":"false, when union reaches [2,3]","rationale":"2 and 3 are each alone when that edge arrives, so their roots differ. union would merge them and report true.","isCorrect":false},{"id":"returns-true","label":"true, because both edges merge","rationale":"Both edges would merge, and the loop would end with two separate groups, {0,1} and {2,3}. The count check is what catches this input.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-pairs","state":{"n":4,"graph":{"nodes":[0,1,2,3],"edges":[[0,1],[2,3]]}}}]}},{"id":"ready-to-code","kind":"info","title":"The edge count, then one union per edge. Now write the function.","workspacePanel":"visualizer","ctaLabel":"Start coding","body":["The function first counts the edges. Any number other than n - 1 returns false.","Every node starts as its own root, with rank 0. find follows the pointers up to a node's root, points the node straight at it, and returns the root.","union finds the roots of an edge's two ends. If they are the same root, it reports false. Otherwise it puts the lower-rank root under the other, adds 1 to the rank of the root on top when the ranks tie, and reports true.","The function sends every edge through union and returns false at the first one that reports false. If none does, it returns true."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"initial-arrays","state":{"n":5,"graph":{"parent":[0,1,2,3,4]},"rows":[{"label":"parent","values":[0,1,2,3,4]},{"label":"rank","values":[0,0,0,0,0]}]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the tree check","workspacePanel":"code","checkpoints":[{"id":"edge-count","title":"Check the edge count first","description":"Return false unless the number of edges is exactly one less than the number of nodes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"guards_relation_count_matches_element_count_minus_one","scope":"edge-count","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the number of edges with n, which rejects every real tree","Rejecting only an empty edge list, which lets every other wrong count through"],"hint":"A tree on n nodes has n - 1 edges, so any other count settles the answer before a single edge is read.","semanticSpec":{"intent":"Prove the relation count is checked against the element count minus one.","doneWhen":"The solution rejects an edge list whose length is not n - 1.","shouldFailWhen":"The code does not compare the edge count with the node-count minus-one bound.","roles":["relation sequence","element count","early rejection"],"mustProve":["The relation sequence length is read.","The count bound is the element count minus one.","A mismatch returns false."],"mustNotAccept":["Comparing the edge count with n.","Checking only whether edges is empty."],"equivalentVariants":["Use != and return false from the mismatch branch.","Use == and return false from the failed-equality branch."],"proofSnippets":[{"id":"py-valid-tree-edge-count","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        return True"}]}},{"id":"init-arrays","title":"Set up parent and rank","description":"Give every node itself as its parent and a rank of 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"initializes_parent_and_rank_state","scope":"init-arrays","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Starting every parent at 0, which puts all the nodes in one group before any edge is read","Giving rank a different length from parent"],"hint":"Before any edge is read there are n groups of one, so every node is its own root and no tree has any height yet.","semanticSpec":{"intent":"Initialize aligned parent and rank state for all n nodes.","doneWhen":"Parent has one self-representative entry per node and rank has one zero seed per node.","shouldFailWhen":"Parent or rank is missing, empty, or sized independently from the node count.","roles":["parent state","rank state","node count"],"mustProve":["Parent is seeded from the node range.","Rank is aligned with parent."],"mustNotAccept":["An empty parent list.","A rank list with a mismatched size."],"equivalentVariants":["Use arrays or lists for parent and rank.","Fill parent with each node's own index."],"proofSnippets":[{"id":"py-valid-tree-init-parent-rank","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n"}]}},{"id":"find-function","title":"Write find with the shortcut","description":"Follow parent pointers from a node up to its root, point the node straight at that root, and return the root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning the node's parent, which is one step up and may not be the root","Finding the root but never storing it, so every call repeats the whole walk"],"hint":"A root is the node that is its own parent. Once the walk has reached it, storing it as the starting node's parent makes the next walk from that node a single step.","semanticSpec":{"intent":"Resolve representatives through parent links and compress each visited node to its root.","doneWhen":"find returns parent[x] after recursively rewriting parent[x] to the root when needed.","shouldFailWhen":"find only reads parent[x] and never writes compressed representatives.","roles":["find helper","parent state","representative"],"mustProve":["find follows parent links until a root.","find writes the resolved root back to the queried node."],"mustNotAccept":["A non-compressing parent lookup.","A helper that ignores the parent state."],"equivalentVariants":["Use recursive path compression.","Use iterative compression with a final root writeback."],"proofSnippets":[{"id":"py-valid-tree-path-compression","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]"}]}},{"id":"union-function","title":"Link one root under the other","description":"In union, find the root of each end of the edge and make one root the parent of the other.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Pointing one end of the edge at the other end without finding their roots","Finding the root of only one end"],"hint":"The pointer to rewrite belongs to a root. Pointing a node from the middle of one group at the other group leaves the nodes above it behind.","semanticSpec":{"intent":"Merge sets by linking representatives rather than raw nodes.","doneWhen":"union finds both roots and writes a parent link between representatives.","shouldFailWhen":"union links raw node ids or never calls find on both endpoints.","roles":["union helper","find helper","representative roots","parent state"],"mustProve":["Both inputs are resolved through find.","Only representatives are linked."],"mustNotAccept":["Raw parent writes without representative lookup.","Merging based on the original endpoints."],"equivalentVariants":["Return a boolean when a merge happens.","Return nothing from a helper used only for merging."],"proofSnippets":[{"id":"py-valid-tree-union-by-root","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            parent[root_y] = root_x"}]}},{"id":"union-by-rank","title":"Let rank decide which root goes under","description":"Put the root with the lower rank under the root with the higher rank. When the ranks tie, pick either one and add 1 to the rank of the root that stays on top.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-by-rank","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the ranks but making the same link in every case","Adding 1 to a rank when the two ranks were different"],"hint":"Rank limits how tall a tree can be. A lower tree fits under a higher one without changing that limit, and two trees with the same limit can produce one that is a step taller.","semanticSpec":{"intent":"Keep union-find trees shallow by using rank-guided representative writes.","doneWhen":"The lower-rank root attaches to the higher-rank root, and a tie increments the chosen root's rank.","shouldFailWhen":"Rank is read but parent writes ignore the rank branches or ties never update rank.","roles":["rank state","representative roots","parent state"],"mustProve":["Rank comparison controls parent writes.","Tie handling increments rank."],"mustNotAccept":["Rank comparisons with no writeback.","Incrementing rank in the wrong branch."],"equivalentVariants":["Attach root_y to root_x on ties.","Attach root_x to root_y on ties if the rank increment matches."],"proofSnippets":[{"id":"py-valid-tree-ranked-union","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1"}]}},{"id":"union-success-return","title":"Report a merge from union","description":"After union has linked two different roots, have it return true.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_successful_merge_boolean","scope":"union-success-return","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning nothing after the link, so the caller cannot tell a merge from a failure"],"hint":"The loop over the edges needs to know whether each edge joined two groups. Reaching the link means this one did.","semanticSpec":{"intent":"Finish the merge helper's boolean contract for the successful merge case.","doneWhen":"The union helper returns true after linking two different representatives.","shouldFailWhen":"The successful merge path returns a non-true value or falls through without a boolean success return.","roles":["union helper","representative link","successful merge"],"mustProve":["Representatives are linked.","The successful merge path returns true."],"mustNotAccept":["Returning false after the parent write.","Returning an empty collection after the parent write."],"equivalentVariants":["Use `return True` after the parent/rank branches complete.","Return true from each successful rank branch."],"proofSnippets":[{"id":"py-valid-tree-union-success-return","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True"}]}},{"id":"check-cycle","title":"Report false when the roots match","description":"In union, before linking anything, return false if both ends of the edge have the same root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"detects_existing_connection_by_find","scope":"check-cycle","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Comparing the two ends of the edge themselves, which only catches an edge from a node to itself","Linking first and looking up the two roots afterward, when they always match"],"hint":"Two nodes with the same root are already connected, so one more edge between them closes a cycle.","semanticSpec":{"intent":"Use representative equality to reject cycle-forming edges.","doneWhen":"The merge helper returns false when both endpoints resolve to the same root.","shouldFailWhen":"The code compares raw endpoints or ignores a failed merge.","roles":["find helper","representative roots","cycle rejection"],"mustProve":["Both endpoints are resolved to representatives.","A same-root comparison returns false."],"mustNotAccept":["Comparing x == y before find.","Skipping the equality guard."],"equivalentVariants":["Return false from union on a same-root edge.","Reject the edge in the loop after comparing representatives."],"proofSnippets":[{"id":"py-valid-tree-cycle-guard","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True"}]}},{"id":"process-edges","title":"Send every edge through union","description":"Loop over the edges, call union with the two ends of each one, and return false as soon as union reports false.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"processes_edges_until_cycle","scope":"process-edges-boolean-reject","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Calling union but ignoring what it reports","Stopping after the first edge"],"hint":"With n - 1 edges there is none to spare, so the first edge that fails to merge already means the graph is not a tree.","semanticSpec":{"intent":"Apply the union helper to every pair in the edge sequence.","doneWhen":"The code loops over edges, calls union with the current edge endpoints, and returns false for a failed merge.","shouldFailWhen":"The edge loop is missing or union is called with constants.","roles":["edge list","edge endpoints","union helper"],"mustProve":["The edge sequence is scanned.","Each scanned pair is passed to union.","A failed merge returns false."],"mustNotAccept":["Calling union once outside a loop.","Using fixed endpoints inside the loop.","Ignoring a failed union result."],"equivalentVariants":["Loop with tuple unpacking.","Loop over edges and index edge[0], edge[1]."],"proofSnippets":[{"id":"py-valid-tree-process-edges","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True\n        for u, v in edges:\n            if not union(u, v):\n                return False"}]}},{"id":"return-success","title":"Return true after the loop","description":"If the loop ends without any edge failing, return true.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_successful_merge_boolean","scope":"return-success","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning false after the loop, which rejects every tree"],"hint":"n - 1 edges that each merged two groups leave exactly one group, and none of them closed a cycle.","semanticSpec":{"intent":"Return the successful tree verdict after the edge scan completes.","doneWhen":"This step is done when the completed merge scan returns true.","shouldFailWhen":"This step should fail if the function returns a non-true value after all merges succeed.","roles":["edge scan","successful verdict"],"mustProve":["The edge sequence is scanned.","The completed edge pass returns true."],"mustNotAccept":["Returning false after the loop.","Returning an empty array or falling off the end."],"equivalentVariants":["Use `return True` after the edge loop.","Use an equivalent boolean true return after all merge checks pass."],"proofSnippets":[{"id":"py-valid-tree-return-success","language":"python","code":"class Solution:\n    def validTree(self, n, edges):\n        if len(edges) != n - 1:\n            return False\n        parent = list(range(n))\n        rank = [0] * n\n        def find(x):\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n        def union(x, y):\n            root_x = find(x)\n            root_y = find(y)\n            if root_x == root_y:\n                return False\n            if rank[root_x] < rank[root_y]:\n                parent[root_x] = root_y\n            elif rank[root_x] > rank[root_y]:\n                parent[root_y] = root_x\n            else:\n                parent[root_y] = root_x\n                rank[root_x] += 1\n            return True\n        for u, v in edges:\n            if not union(u, v):\n                return False\n        return True"}]}}]},{"id":"complete","kind":"complete","title":"A tree is n - 1 edges that each join two groups","workspacePanel":"code","takeaways":[{"title":"Count the edges first","body":"A tree on n nodes has exactly n - 1 edges, so any other count returns false before a single edge is read."},{"title":"With n - 1 edges, every edge has to merge","body":"If every edge joins two different groups, n groups end as one with no cycle. One edge inside a group closes a cycle and leaves a node unconnected, so a single false from union is enough to return false."},{"title":"Roots stand for groups","body":"find(x) follows `parent` up to the node that points to itself. Two nodes are in the same group exactly when find returns the same root for both, and union always links one root under the other."},{"title":"Close to O(n) time, O(n) space","body":"The count check is one comparison. After it there are n - 1 edges. The shortcuts in find and the rank rule keep the walks so short that all the unions take O(n α(n)) time in total. α(n) is at most 4 for any n a computer can hold. `parent` and `rank` take O(n) space."}]}],"slidesOrigin":"authored","progressRevision":"graph-valid-tree-2026-11-20-count-then-merge"}}
