{"id":"find-if-path-exists-in-graph","title":"Find if Path Exists in Graph","difficulty":"easy","patterns":["union-find"],"primaryConcept":"graph-union-find-connectivity","concepts":["graph-union-find-connectivity","graph-components"],"problemForm":"intro","companies":["Google","Amazon","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"},"source":{"strategy":"fixed","value":0},"destination":{"strategy":"fixed","value":1}},"constraints":["mixed-components"]},"description":"You are given an undirected graph with `n` nodes labeled from `0` to `n - 1`, an edge list `edges`, and two nodes `source` and `destination`.\n\nReturn `true` if there is a path from `source` to `destination`, otherwise return `false`.","examples":[{"input":"n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2","output":"true","explanation":"Node 0 connects to node 2 directly and also through node 1."},{"input":"n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5","output":"false","explanation":"Nodes 0 and 5 are in different connected components."}],"constraints":[{"id":"1-n-2-10-5","text":"1 <= n <= 2 * 10^5","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":200000}},{"id":"0-edges-length-2-10-5","text":"0 <= len(edges) <= 2 * 10^5","check":{"kind":"sizeRange","target":"edges","measure":"arrayLength","min":0,"max":200000}},{"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":"0-source-destination-n","text":"0 <= source, destination < n","check":[{"kind":"valueRange","target":"source","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"destination","selector":"value","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-edges","text":"There are no duplicate edges"}],"starterCode":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        # Your code here\n        pass","functionName":"validPath","testCases":[{"id":"1","input":{"n":3,"edges":[[0,1],[1,2],[2,0]],"source":0,"destination":2},"expected":true,"description":"All nodes are connected."},{"id":"2","input":{"n":6,"edges":[[0,1],[0,2],[3,5],[5,4],[4,3]],"source":0,"destination":5},"expected":false,"description":"Source and destination are in separate components."},{"id":"3","input":{"n":1,"edges":[],"source":0,"destination":0},"expected":true,"description":"A node always has a path to itself."},{"id":"4","input":{"n":4,"edges":[[0,1],[2,3]],"source":1,"destination":0},"expected":true,"description":"Undirected edges connect both directions."},{"id":"5","input":{"n":5,"edges":[[0,1],[1,2],[3,4]],"source":2,"destination":4},"expected":false,"description":"Two components remain disconnected."},{"id":"h1","input":{"n":5,"edges":[[0,1],[1,2],[2,3],[3,4]],"source":0,"destination":4},"description":"A simple chain reaches the far end.","expected":true},{"id":"h2","input":{"n":5,"edges":[[0,1],[2,3]],"source":0,"destination":4},"description":"An isolated destination remains unreachable.","expected":false},{"id":"h3","input":{"n":2,"edges":[],"source":1,"destination":1},"description":"A node always reaches itself, even when isolated.","expected":true},{"id":"h4","input":{"n":6,"edges":[[0,1],[1,2],[3,4],[4,5]],"source":2,"destination":5},"description":"Two components stay disconnected.","expected":false},{"id":"h5","input":{"n":6,"edges":[[0,1],[1,2],[2,0],[2,3],[3,4]],"source":0,"destination":4},"description":"A cycle with a tail still yields a path.","expected":true},{"id":"direct-edge-listed-last","input":{"n":4,"edges":[[0,3],[2,1],[3,1]],"source":3,"destination":1},"expected":true,"description":"The edge between source and destination comes last, after both nodes have already joined other nodes."},{"id":"source-with-no-edges","input":{"n":3,"edges":[[0,2]],"source":1,"destination":2},"expected":false,"description":"There are more nodes than edges, and the source has no edges at all."},{"id":"direct-edge-after-longer-chains","input":{"n":4,"edges":[[0,2],[1,3],[0,1],[3,2],[0,3]],"source":3,"destination":2},"expected":true,"description":"Source and destination share an edge, listed after edges that link every node."}],"hints":[{"level":1,"content":"A path exists exactly when source and destination end up in the same connected component."},{"level":2,"content":"Union every edge, then compare the representative roots of source and destination."},{"level":3,"content":"Use path compression in find and union by rank so large graphs stay efficient."}],"guidedFlow":{"version":2,"progressRevision":"find-if-path-exists-in-graph-2026-07-19-honest-union-find-derivation","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dfs-from-source","name":"DFS from source","summary":"Build an adjacency list and search from source until destination is found.","decisionReason":"DFS answers one source-to-destination query by building an adjacency list and re-searching the graph for that pair. Union-find instead merges every edge once into a flat parent forest, so the connectivity query collapses to a single root comparison and repeated queries answer in near-constant time on the reusable component structure.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time and uses O(n + e) space."],"isOptimal":false},{"id":"union-find-components","name":"Union Find components","summary":"Merge edge endpoints into components and compare the final roots.","decisionReason":"Union-find turns each undirected edge into a component merge in the parent array. After all merges, source and destination are connected exactly when find(source) and find(destination) return the same root.","complexity":{"time":"O((n+e)*alpha(n))","space":"O(n)"},"tradeoffs":["Runs in O((n+e)*alpha(n)) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-arrays","title":"Initialize parent and rank arrays","description":"Create one parent entry and one rank entry for every node.","commonMistakes":["Creating arrays sized by edges instead of nodes","Forgetting that each node starts as its own parent"],"hint":"Parent starts as [0, 1, 2, ...], and every rank starts at 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"}]},"semanticSpec":{"intent":"Initialize union-find parent and rank state for all n nodes.","doneWhen":"Each node is its own parent and the rank array is initialized before any unions run.","shouldFailWhen":"Parent is missing, rank is missing, or either structure has the wrong size.","roles":["parent array","rank array","node ids"],"mustProve":["Parent contains one identity entry per node.","Rank contains one initial value per node.","Both structures are initialized before processing edges."],"mustNotAccept":["Initializing parent from the edge count.","Using a shared or missing rank structure."],"equivalentVariants":["Use list(range(n)) for parent and a zero-filled rank array.","Use equivalent arrays or vectors in another language."],"proofSnippets":[{"id":"py-path-exists-init-arrays","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n"}]}},{"id":"find-function","title":"Implement path-compressed find","description":"Return the representative root and compress the path on the way back.","commonMistakes":["Returning only the immediate parent","Forgetting to write the compressed parent"],"hint":"If parent[x] is not x, recursively find the root and store it back into parent[x].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Define a find helper that follows parent links to the root and compresses intermediate nodes.","doneWhen":"The helper recursively resolves the root and writes the root back into the parent array.","shouldFailWhen":"The helper does not recurse, does not write compression, or returns a non-root parent.","roles":["find helper","parent array","representative root"],"mustProve":["The helper checks whether a node is already its own parent.","The helper recursively resolves the root.","The helper writes the compressed root back to parent[x]."],"mustNotAccept":["Returning parent[x] without resolving the full root.","A helper that never mutates parent during compression."],"equivalentVariants":["Use recursive path compression.","Use iterative path compression with an equivalent parent rewrite."],"proofSnippets":[{"id":"py-path-exists-find-function","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]"}]}},{"id":"union-roots","title":"Union by representative roots","description":"Use find on both endpoints and only connect the two roots.","commonMistakes":["Linking raw endpoints instead of roots","Continuing when both endpoints already share a root"],"hint":"Call find on both endpoint ids, then connect the returned roots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Define union so it resolves endpoint roots before linking components.","doneWhen":"Union calls find for both endpoints and links only different roots.","shouldFailWhen":"Union links raw nodes, skips find, or fails to handle already-connected endpoints.","roles":["union helper","first root","second root","parent array"],"mustProve":["Union calls the find helper for both endpoints.","Union compares roots before linking.","Union writes a parent link between roots only."],"mustNotAccept":["Assigning parent[a] = b directly without root lookup.","Linking a component to itself."],"equivalentVariants":["Resolve both roots and connect one root under the other.","Use a boolean-returning union as long as it links roots."],"proofSnippets":[{"id":"py-path-exists-union-roots","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            parent[root_b] = root_a"}]}},{"id":"union-by-rank","title":"Apply union by rank","description":"Attach the shallower root under the deeper root and increase rank on ties.","commonMistakes":["Updating rank on every union","Comparing raw endpoint ranks instead of root ranks"],"hint":"Only increase rank when both roots have the same rank.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-by-rank","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Use rank to keep the union-find forest shallow.","doneWhen":"Union compares root ranks, links the lower-rank root, and increments rank only for equal-rank roots.","shouldFailWhen":"Rank is ignored, updated for non-ties, or read from non-root nodes.","roles":["rank array","root rank comparison","tie rank increment"],"mustProve":["Root ranks are compared before linking.","The lower-rank root is attached under the higher-rank root.","The chosen root's rank increases on ties."],"mustNotAccept":["Always attaching one root regardless of rank.","Incrementing both ranks or incrementing on every merge."],"equivalentVariants":["Use union by rank.","Use union by size if represented through an equivalent rank-like auxiliary array."],"proofSnippets":[{"id":"py-path-exists-union-by-rank","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1"}]}},{"id":"process-edges","title":"Union every graph edge","description":"Scan the edge list and union both endpoints of each undirected edge.","commonMistakes":["Only processing edges that touch source","Treating edges as directed"],"hint":"Every edge tells you two nodes belong to the same component.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Merge all endpoint pairs from the edge list into union-find components.","doneWhen":"The solution loops over every edge pair and calls union on its two endpoints.","shouldFailWhen":"Some edges are skipped, endpoints are not both used, or the union helper is not called.","roles":["edge list","edge endpoints","union helper"],"mustProve":["The edge list is scanned.","Each scanned pair provides both endpoints.","The union helper receives those endpoints."],"mustNotAccept":["Checking only source-adjacent edges.","Building components without using the union helper."],"equivalentVariants":["Use `for a, b in edges` and call union on a and b.","Use indexed edge access as long as both endpoints are merged."],"proofSnippets":[{"id":"py-path-exists-process-edges","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1\n\n        for a, b in edges:\n            union(a, b)"}]}},{"id":"check-connectivity","title":"Compare source and destination roots","description":"After all unions, return whether source and destination have the same representative root.","commonMistakes":["Comparing parent[source] and parent[destination] without find","Returning true after seeing any edge"],"hint":"Use find on both query nodes after all edges have been processed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_existing_connection_verdict_by_find","scope":"check-cycle","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Answer the connectivity query by comparing final representative roots.","doneWhen":"The function returns whether find(source) equals find(destination) after processing all edges.","shouldFailWhen":"The code compares raw parents, checks before processing all edges, or ignores one query node.","roles":["source node","destination node","representative roots","boolean result"],"mustProve":["The final check calls find on source.","The final check calls find on destination.","The return compares those representative roots."],"mustNotAccept":["Returning parent[source] == parent[destination] without find.","Returning whether either node appears in any edge."],"equivalentVariants":["Return `find(source) == find(destination)` directly.","Store both roots in temporaries and compare them."],"proofSnippets":[{"id":"py-path-exists-check-connectivity","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if root_a == root_b:\n                return\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1\n\n        for a, b in edges:\n            union(a, b)\n\n        return find(source) == find(destination)"}]}}],"slides":[{"id":"read-the-problem","kind":"info","chapter":"The graph","eyebrow":"Read the problem","title":"Is there any path between two nodes?","workspacePanel":"problem","body":["You are given an undirected graph with n nodes and a list of edges. Two of the nodes are marked source and destination. Return true if you can walk from source to destination along edges, false if you cannot.","Reachability can pass through any number of intermediate nodes. Each undirected edge joins two groups, so the final question is whether source and destination belong to the same group."]},{"id":"approach-selection","kind":"case-probe","chapter":"The idea","eyebrow":"Read one edge","title":"The edge [1,2] joins groups {0,1} and {2,3}. What does that establish?","workspacePanel":"visualizer","summary":"Edges [0,1] and [2,3] have already formed two separate connected groups.","options":[{"id":"whole-groups","label":"Every node in one group can now reach every node in the other","rationale":"Any member can travel inside its old group, cross the new edge, then travel inside the other group. One edge therefore merges the two whole connected components.","isCorrect":true},{"id":"endpoints-only","label":"Only nodes 1 and 2 become connected","rationale":"0 already reaches 1 and 2 already reaches 3, so the new edge also creates paths between all of those members."},{"id":"no-change","label":"Nothing changes until a direct edge joins source to destination","rationale":"A path may use intermediate nodes. The new edge creates 0-1-2-3 even though 0 and 3 have no direct edge."}],"answer":"The edge merges the two whole connected groups. Instead of creating only one new connection, it changes which component every member belongs to. What state could preserve that fact as more edges arrive?","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[["0","1"],["2","3"]],"activeEdges":[["1","2"]]}}}]}},{"id":"component-state-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Choose the state","title":"After each edge, what should we preserve for the final reachability question?","workspacePanel":"visualizer","summary":"The edges arrive one at a time, and each one may combine two whole connected groups.","options":[{"id":"component-membership","label":"Which connected component each node currently belongs to","rationale":"Each edge can merge two component memberships. After every edge is processed, matching memberships answer whether the endpoints are connected.","isCorrect":true},{"id":"last-edge","label":"Only the endpoints of the most recent edge","rationale":"Earlier edges still contribute to later paths, so remembering only the newest pair loses connectivity that has already been established."},{"id":"all-routes","label":"The exact route between every pair of nodes","rationale":"The result asks only whether a route exists. Full routes contain far more information than the final yes-or-no comparison needs."}],"answer":"Preserve the current connected-component membership of every node. Then each edge combines memberships, and the final query only compares the memberships of source and destination.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"component-memberships","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[["0","1"],["2","3"],["1","2"]]}}}]}},{"id":"component-representation-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Represent the groups","title":"Which representation can name a group and combine two groups with one link?","workspacePanel":"visualizer","summary":"We need to identify a node's current component, and each edge may merge two entire components.","options":[{"id":"parent-forest","label":"A rooted parent tree for each component","rationale":"Following parents gives every member one root as its group name. Linking one root beneath another combines the two whole trees with one update.","isCorrect":true},{"id":"label-every-node","label":"A component label copied onto every node","rationale":"Labels identify the groups, but a merge may require finding and relabeling every member of one component instead of changing one link."},{"id":"newest-edge","label":"Only the most recently processed edge","rationale":"One edge does not retain the components built by earlier edges, so it cannot answer the final membership comparison."}],"answer":"Use one rooted parent tree per component. The root names the group, and linking two roots combines both groups with one structural update.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"candidate-parent-forest","state":{"graph":{"parent":[0,0,2,2]}}}]}},{"id":"union-find-route","kind":"info","chapter":"The idea","eyebrow":"Name the structure","title":"Union Find maintains exactly those memberships","workspacePanel":"visualizer","body":["A DFS or BFS from source is also a correct O(n + e) solution for this single query. The parent-forest representation we just derived is called Union Find: find follows parents to identify a component, and union links two roots to combine components.","Each edge updates the current component partition. After the last edge, the path question becomes a root comparison. Next we will make both parent-tree operations precise."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"union-find-components","state":{"graph":{"nodes":[{"id":"0","label":"0"},{"id":"1","label":"1"},{"id":"2","label":"2"},{"id":"3","label":"3"}],"edges":[["0","1"],["2","3"],["1","2"]]}}}]}},{"id":"point-to-rep","kind":"info","chapter":"The idea","eyebrow":"Track the groups","title":"Each node points to a representative","workspacePanel":"visualizer","body":["Give every node a parent. At the start each node is its own parent, so each sits alone in its own group.","Following the parent links upward from any node lands on the root of its group, the single node that points to itself."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rep-state","state":{"graph":{"parent":[0,1,2,3,4]}}}]}},{"id":"same-root","kind":"case-probe","chapter":"The idea","eyebrow":"Connect the representation","title":"Nodes 0 and 2 climb to the same root. What does that mean in the original graph?","workspacePanel":"visualizer","summary":"The maintained parent forest places 0 and 2 in one group even though they do not share a direct edge.","options":[{"id":"same-root","label":"The two endpoints are mutually reachable","rationale":"Each union mirrors a real graph edge. Landing at one root means those edge merges placed both nodes in the same connected component, which is exactly the existence of some path.","isCorrect":true},{"id":"direct-edge","label":"They must also share a direct edge before a path exists","rationale":"A connected component records reachability through any number of intermediate nodes, so a direct edge is unnecessary."},{"id":"same-parent","label":"The parent forest says nothing about graph reachability","rationale":"The forest was built only by merging endpoints of real graph edges, so its groups are precisely the graph's connected components."}],"answer":"They belong to one connected component, so some path exists. Because every union came from a real edge, comparing the two final roots answers the original reachability question.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"same-root-state","state":{"graph":{"parent":[0,0,0,3,4]}}}]}},{"id":"bridge-merge","kind":"info","chapter":"The idea","eyebrow":"Know what is preserved","title":"The groups prove existence without storing the route","workspacePanel":"visualizer","body":["After [1,2] merges {0,1} with {2,3}, nodes 0 and 3 share a component, so the answer is true. The parent forest does not preserve the particular route 0-1-2-3, and this problem does not ask for it.","That distinction is why one final root comparison is sufficient here. If the task asked you to return the actual path, a DFS or BFS with predecessor links would preserve information Union Find intentionally throws away."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge-state","state":{"graph":{"parent":[0,0,0,2,4]}}}]}},{"id":"link-roots","kind":"case-probe","chapter":"The idea","eyebrow":"Merge the groups","title":"An edge joins two nodes in different groups. What do you link?","workspacePanel":"visualizer","summary":"The edge [1, 2] connects node 2 with the component containing 0 and 1.","options":[{"id":"roots","label":"Attach one representative to the other","rationale":"Linking root to root folds both groups in one move, so every member still climbs to a single shared root afterward.","isCorrect":true},{"id":"direct","label":"Point node 2 straight at node 1","rationale":"Aiming a node at a non-root works by luck here but leaves chains and stale roots in general. Resolve to the roots first, then link those."},{"id":"nothing","label":"Nothing, they are already connected","rationale":"Node 2 climbs to a different root than node 1, so this edge performs a real merge."}],"answer":"Link the roots. Joining root to root merges both groups at once and keeps later lookups short.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"link-state","state":{"graph":{"parent":[0,0,2,3,4],"current":2,"highlighted":[0],"activeEdges":[[1,2]]}}}]}},{"id":"same-group-edge-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Handle a redundant edge","title":"Both endpoints already climb to root 0. What should union do with edge [1,2]?","workspacePanel":"visualizer","summary":"The parent forest already places nodes 1 and 2 in the same connected component.","options":[{"id":"no-op","label":"Do nothing because the edge does not change the groups","rationale":"The two roots are already equal, so the endpoints were connected before this edge. Linking again cannot merge anything new and risks corrupting the parent tree.","isCorrect":true},{"id":"link-endpoints","label":"Point node 2 directly at node 1","rationale":"Union changes representative roots, not arbitrary endpoints. Here there are not even two different roots to join."},{"id":"new-root","label":"Create a new representative just for this edge","rationale":"The component already has a representative. A redundant edge changes no membership and needs no new state."}],"answer":"Do nothing when the roots match. Union links two distinct roots; an edge inside one existing component leaves the partition unchanged.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"same-group-edge-state","state":{"graph":{"parent":[0,0,0,3,4],"current":1,"highlighted":[2],"activeEdges":[[1,2]]}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Merge every edge, then compare two roots","workspacePanel":"visualizer","body":["Every node starts as its own root. For each edge, resolve both endpoints to their roots. If the roots differ, link one under the other; if they match, that edge changes nothing.","After every edge is processed, compare the root of source with the root of destination. Equal roots mean a path exists. Watch the groups merge on n = 5, edges = [[0,1], [2,3], [1,2]], with source 0 and destination 3."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"parent":[0,1,2,3,4]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the unions","title":"Trace the merging groups","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"union-01","state":{"graph":{"parent":[0,0,2,3,4],"current":1,"highlighted":[0],"activeEdges":[[1,0]]}}},{"id":"union-23","state":{"graph":{"parent":[0,0,2,2,4],"current":3,"highlighted":[2],"activeEdges":[[3,2]]}}},{"id":"union-12","state":{"graph":{"parent":[0,0,0,2,4],"current":2,"highlighted":[0],"activeEdges":[[2,0]]}}},{"id":"compare","state":{"graph":{"parent":[0,0,0,2,4],"current":3,"highlighted":[0]}}}]},"beats":[{"id":"union-01","title":"Edge [0, 1]: the two nodes are in different groups. Are source and destination connected yet?","summary":"Two singletons with different roots.","prompt":"Source is 0 and destination is 3. Only nodes 0 and 1 have been linked so far.","options":[{"id":"merge-no","label":"They merge into one group, but 0 and 3 are still apart","rationale":"Different roots mean a real merge, so 0 and 1 join. Node 3 has its own root, so source and destination are not connected yet.","isCorrect":true},{"id":"connected","label":"Yes, source and destination are now connected","rationale":"This edge only joins 0 and 1. Node 3 sits in its own group, so find(0) and find(3) differ."},{"id":"skip","label":"Nothing changes","rationale":"0 and 1 start in separate groups, so the edge does merge them into one."}],"answer":"They merge, but 0 and 3 stay apart. {0,1} is one group now, while 3 is still on its own, so find(0) and find(3) differ."},{"id":"union-23","title":"Edge [2, 3]: nodes 2 and 3 join. Does this connect 0 and 3?","summary":"Nodes 2 and 3 are processed after {0,1}.","prompt":"Group {0,1} already exists. This edge links 2 and 3.","options":[{"id":"separate","label":"No, 0 remains separate from 3","rationale":"This edge merges 2 and 3 into their own group. Node 0 is in the {0,1} group, so the two roots are still different.","isCorrect":true},{"id":"yes","label":"Yes, 3 now reaches 0","rationale":"Nothing yet links group {2,3} to group {0,1}. find(0) is 0 and find(3) is 2, so they differ."},{"id":"cycle","label":"It repeats a connection that already exists","rationale":"2 and 3 start in separate groups, so this edge merges them."}],"answer":"No. This builds the second group {2,3}. Source still has root 0 and destination still has root 2, so they are not connected."},{"id":"union-12","title":"Edge [1, 2]: it joins group {0,1} to group {2,3}. Now are source and destination connected?","summary":"The bridging edge merges the two groups.","prompt":"find(1) is 0 and find(2) is 2, two different roots.","options":[{"id":"connected","label":"Yes, the merge puts 0 and 3 under one root","rationale":"Linking the roots folds {0,1} and {2,3} into one group, so 0, 1, 2, 3 all climb to one root and the path 0-1-2-3 exists.","isCorrect":true},{"id":"only-edge","label":"Only 1 and 2 connect, not 0 and 3","rationale":"Merging the roots connects every member of both groups, so 0 rides with 1 and 3 rides with 2."},{"id":"no","label":"No, they need a direct 0-3 edge","rationale":"A path may pass through other nodes. 0-1-2-3 is a valid walk, so no direct edge is required."}],"answer":"Yes. The roots of {0,1} and {2,3} link, so all four nodes share one root and source reaches destination through 0-1-2-3."},{"id":"compare","title":"All edges are processed. What does comparing the roots of source and destination return?","summary":"Node 4 never got an edge.","prompt":"find(0) is 0 and find(3) is 0. Node 4 still has root 4.","options":[{"id":"true","label":"true, because find(0) equals find(3)","rationale":"Both source and destination climb to root 0, so they share a group and a path exists. Node 4 sits alone but is never queried.","isCorrect":true},{"id":"false","label":"false, because node 4 is still separate","rationale":"The answer compares only source and destination. Node 4 being isolated does not affect whether 0 reaches 3."},{"id":"depends","label":"It depends on the edge order","rationale":"Once every edge is unioned, the final groups are the same regardless of order, so the root comparison is fixed."}],"answer":"true. find(0) and find(3) both reach root 0, so a path exists. Node 4 stays isolated but is never compared."}]},{"id":"early-check-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Could you read off the verdict the moment each edge is merged?","workspacePanel":"trace","summary":"After merging each edge, compare find(source) with find(destination): the moment they match, return true, otherwise return false. It looks reasonable, and it answers correctly whenever the edge that links source and destination comes early in the list. Watch it on edges [[0,1], [1,2]] with source 0 and destination 2, where the linking edge comes second.","pitfall":"The code below merges one edge, then commits to a verdict from that partial state: true if the roots already match, false otherwise.","whyItMatters":"Returning a verdict mid-loop reads the connection off a graph that is only half built. Here the bridging edge [1,2] is the second edge, so the loop bails on the first edge before it ever runs and reports false on a graph that is actually connected. Union every edge first, then compare the roots once at the end.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def validPath(n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n    parent: list[int] = [i for i in range(n)]\n\n    def find(x: int) -> int:\n        while parent[x] != x:\n            x = parent[x]\n        return x\n\n    for a, b in edges:\n        parent[find(b)] = find(a)\n        if find(source) == find(destination):\n            return True\n        return False\n    return True","steps":[{"id":"before","title":"Before the loop: every node is its own group","codeLine":2,"summary":"source is 0, destination is 2, and nothing is linked yet.","state":{"graph":{"parent":[0,1,2]}}},{"id":"union-01","title":"Edge [0,1]: nodes 0 and 1 merge","codeLine":10,"summary":"find(0) becomes 0 and find(1) becomes 0, so {0,1} is one group.","state":{"graph":{"parent":[0,0,2],"current":1,"highlighted":[0],"activeEdges":[[1,0]]}}},{"id":"check","title":"The verdict is read off after only one edge, while node 2 is still alone","codeLine":11,"summary":"find(0) is 0 and find(2) is 2, so the roots do not match yet.","state":{"graph":{"parent":[0,0,2],"current":0,"highlighted":[2]}}},{"id":"bail","title":"It commits to false, before the bridging edge runs","codeLine":13,"summary":"The function returns false here, so edge [1,2] never gets to connect 1 and 2.","state":{"graph":{"parent":[0,0,2]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const parent = Array.from({ length: n }, (_, index) => index);\nfunction find(x) {\n    while (parent[x] !== x) {\n        x = parent[x];\n    }\n    return x;\n}\nfor (const [a, b] of edges) {\n    parent[find(b)] = find(a);\n    if (find(source) === find(destination)) {\n        return true;\n    }\n    return false;\n}\nreturn true;","lineMap":{"2":1,"5":3,"6":4,"7":6,"9":8,"10":9,"11":10,"12":11,"13":13,"14":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"6":{"startLine":4,"endLine":5},"7":{"startLine":6,"endLine":7},"12":{"startLine":11,"endLine":12},"13":{"startLine":13,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const parent = Array.from({ length: n }, (_, index) => index);\nfunction find(x: number): number {\n    while (parent[x] !== x) {\n        x = parent[x];\n    }\n    return x;\n}\nfor (const [a, b] of edges) {\n    parent[find(b)] = find(a);\n    if (find(source) === find(destination)) {\n        return true;\n    }\n    return false;\n}\nreturn true;","lineMap":{"2":1,"5":3,"6":4,"7":6,"9":8,"10":9,"11":10,"12":11,"13":13,"14":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"6":{"startLine":4,"endLine":5},"7":{"startLine":6,"endLine":7},"12":{"startLine":11,"endLine":12},"13":{"startLine":13,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int find(int x, List<Integer> parent) {\n    while (parent.get(x) != x) {\n        x = parent.get(x);\n    }\n    return x;\n}\n\nList<Integer> parent = new ArrayList<>();\nfor (int i = 0; i < n; i++) {\n    parent.add(i);\n}\nfor (List<Integer> edge : edges) {\n    int a = edge.get(0);\n    int b = edge.get(1);\n    parent.set(find(b, parent), find(a, parent));\n    if (find(source, parent) == find(destination, parent)) {\n        return true;\n    }\n    return false;\n}\nreturn true;","lineMap":{"2":8,"5":2,"6":3,"7":5,"9":12,"10":15,"11":16,"12":17,"13":19,"14":21},"statementBundles":{"2":{"startLine":8,"endLine":11},"6":{"startLine":3,"endLine":4},"7":{"startLine":5,"endLine":6},"9":{"startLine":12,"endLine":14},"12":{"startLine":17,"endLine":18},"13":{"startLine":19,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> parent = Enumerable.Range(0, n).Select(i => i).ToList();\nint Find(int x) {\n    while (parent[x] != x) {\n        x = parent[x];\n    }\n    return x;\n    return 0;\n}\nforeach (var item in edges) {\n    int a = item[0];\n    int b = item[1];\n    parent[Find(b)] = Find(a);\n    if (Find(source) == Find(destination)) {\n        return true;\n    }\n    return false;\n}\nreturn true;","lineMap":{"2":1,"5":3,"6":4,"7":6,"9":9,"10":12,"11":13,"12":14,"13":16,"14":18},"statementBundles":{"2":{"startLine":1,"endLine":2},"6":{"startLine":4,"endLine":5},"7":{"startLine":6,"endLine":8},"9":{"startLine":9,"endLine":11},"12":{"startLine":14,"endLine":15},"13":{"startLine":16,"endLine":17}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> parent = tracecodeIntRange(0, n);\nauto find = [&]( int x ) -> int {\n    while (parent[x] != x) {\n        x = parent[x];\n    }\n    return x;\n};\nfor (vector<int> item : edges) {\n    int a = item[0];\n    int b = item[1];\n    parent[find(b)] = find(a);\n    if (find(source) == find(destination)) {\n        return true;\n    }\n    return false;\n}\nreturn true;","lineMap":{"2":1,"5":3,"6":4,"7":6,"9":8,"10":11,"11":12,"12":13,"13":15,"14":17},"statementBundles":{"2":{"startLine":1,"endLine":2},"6":{"startLine":4,"endLine":5},"7":{"startLine":6,"endLine":7},"9":{"startLine":8,"endLine":10},"12":{"startLine":13,"endLine":14},"13":{"startLine":15,"endLine":16}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["On the sample, unioning every edge and comparing the two roots at the end found the path, which only appeared once the bridging edge merged the two groups.","Two thin graphs are worth a look before you code: one where source and destination are the same node, and one where the graph has no edges at all."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"graph":{"parent":[0,1,2]}}}]}},{"id":"same-node","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"source and destination are the same node. What should the answer be?","workspacePanel":"visualizer","summary":"n = 1, edges = [], source = 0, destination = 0.","options":[{"id":"true","label":"true","rationale":"Each node starts as its own root, so find(0) and find(0) trivially match. The zero-length path from a node to itself always exists.","isCorrect":true},{"id":"needs-edge","label":"false, there is no edge to travel","rationale":"A path of length zero needs no edge. Because the comparison is find(source) == find(destination), the same node returns true with no edges at all."},{"id":"undefined","label":"It is undefined with no edges","rationale":"The roots are initialized before any edge runs, so the comparison is well defined and returns true here."}],"answer":"true. Comparing roots gives find(0) == find(0), which holds with no edges, so a node always reaches itself.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"same-node-state","state":{"graph":{"parent":[0],"current":0}}}]}},{"id":"no-edges","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"The graph has no edges and source differs from destination. What is returned?","workspacePanel":"visualizer","summary":"n = 3, edges = [], source = 0, destination = 2.","options":[{"id":"false","label":"false, each node is still its own root","rationale":"With no edges, no merge runs, so find(0) is 0 and find(2) is 2. Different roots mean no path.","isCorrect":true},{"id":"true-default","label":"true, nodes default to connected","rationale":"Initializing each node as its own group is what keeps disconnected nodes apart, so distinct nodes with no edge return false."},{"id":"error","label":"It errors because the edge list is empty","rationale":"An empty edge list simply skips the union loop. The roots are already initialized, so the comparison still runs."}],"answer":"false. No edge merges anything, so 0 and 2 keep their own roots and the comparison reports no path.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-edges-state","state":{"graph":{"parent":[0,1,2]}}}]}},{"id":"correct-before-fast","kind":"info","chapter":"Code","eyebrow":"Separate correctness from speed","title":"The component rule works, but a root can be expensive to reach","workspacePanel":"visualizer","body":["The algorithm is already correct if find follows parent links to a root and union links one root beneath the other. A chain such as 0 → 1 → 2 → 3 → 4 still names component 4 correctly.","The cost appears when later edges ask for find(0) or find(1) again: the same long links are walked repeatedly. Since the first walk already discovered root 4, can it leave the structure cheaper for the next lookup?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-long-find","state":{"graph":{"parent":[1,2,3,4,4],"current":0,"highlighted":[0,1,2,3,4]}}}]}},{"id":"path-compression-probe","kind":"case-probe","chapter":"Code","eyebrow":"Shorten future lookups","title":"find(0) walks 0 → 1 → 2 → 3 → 4. What should it do on the way back?","workspacePanel":"visualizer","summary":"Root 4 is the correct answer either way. The question is how to reuse that completed walk the next time one of these nodes is searched.","options":[{"id":"compress","label":"Point every visited node directly to root 4","rationale":"The walk just proved that every visited node belongs to root 4. Rewriting those parent links preserves the component and makes later finds much shorter.","isCorrect":true},{"id":"leave-chain","label":"Leave the entire chain unchanged","rationale":"That is correct but throws away the completed lookup, forcing the same long climb on future finds."},{"id":"reverse-chain","label":"Reverse every parent link toward node 0","rationale":"Node 0 is not the representative that find discovered. Reversing the chain changes the chosen root instead of merely shortening access to it."}],"answer":"Point the visited nodes directly to root 4. This path compression keeps the component unchanged while turning later climbs through that path into nearly direct lookups.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"long-parent-chain","state":{"graph":{"parent":[1,2,3,4,4],"current":0,"highlighted":[4]}}}]}},{"id":"rank-probe","kind":"case-probe","chapter":"Code","eyebrow":"Avoid new long chains","title":"One root has rank 2 and the other has rank 1. Which root should become the child?","workspacePanel":"visualizer","summary":"Both link directions merge the same components, but one choice keeps the resulting parent tree shallower.","options":[{"id":"shallow-under-deep","label":"Attach the rank-1 root under the rank-2 root","rationale":"The smaller tree fits below the deeper root without increasing the larger tree's height, keeping future root walks short.","isCorrect":true},{"id":"deep-under-shallow","label":"Attach the rank-2 root under the rank-1 root","rationale":"That places the deeper tree below the shallower one and can add another level to every path in the larger tree."},{"id":"link-endpoints-rank","label":"Ignore both roots and link the original edge endpoints","rationale":"The component structure is represented by roots. Linking arbitrary endpoints can create stale or unnecessarily deep parent chains."}],"answer":"Attach the shallower root under the deeper root. Rank records the relative tree depth; when ranks tie, choose either root and increase the chosen root's rank by one.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unequal-rank-roots","state":{"graph":{"parent":[0,0,0,3,3],"rank":[2,0,0,1,0],"current":0,"highlighted":[3]}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Code the rule","title":"Build the connectivity check","workspacePanel":"visualizer","summary":"Each node starts alone, edges merge the groups, and one root comparison answers the query.","body":["Now build it. Give every node its own parent and rank, then write find so it climbs to the root and rewrites the links it passes so the next lookup is shorter. Union resolves both endpoints to their roots and links them, attaching the shallower root under the deeper one so the trees stay flat.","With those pieces in place, walk the edge list and union both endpoints of every edge. After the last edge, return whether source and destination climb to the same root."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"parent":[0,1,2,3,4]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the connectivity check","summary":"Build the parent forest, then merge every edge and compare the two roots.","workspacePanel":"code","checkpoints":[{"id":"init-arrays","title":"Initialize parent and rank arrays","description":"Create one parent entry and one rank entry for every node.","commonMistakes":["Creating arrays sized by edges instead of nodes","Forgetting that each node starts as its own parent"],"hint":"Parent starts as [0, 1, 2, ...], and every rank starts at 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"}]},"semanticSpec":{"intent":"Initialize union-find parent and rank state for all n nodes.","doneWhen":"Each node is its own parent and the rank array is initialized before any unions run.","shouldFailWhen":"Parent is missing, rank is missing, or either structure has the wrong size.","roles":["parent array","rank array","node ids"],"mustProve":["Parent contains one identity entry per node.","Rank contains one initial value per node.","Both structures are initialized before processing edges."],"mustNotAccept":["Initializing parent from the edge count.","Using a shared or missing rank structure."],"equivalentVariants":["Use list(range(n)) for parent and a zero-filled rank array.","Use equivalent arrays or vectors in another language."],"proofSnippets":[{"id":"py-path-exists-init-arrays","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n"}]}},{"id":"find-function","title":"Implement path-compressed find","description":"Return the representative root and compress the path on the way back.","commonMistakes":["Returning only the immediate parent","Forgetting to write the compressed parent"],"hint":"If parent[x] is not x, recursively find the root and store it back into parent[x].","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Define a find helper that follows parent links to the root and compresses intermediate nodes.","doneWhen":"The helper recursively resolves the root and writes the root back into the parent array.","shouldFailWhen":"The helper does not recurse, does not write compression, or returns a non-root parent.","roles":["find helper","parent array","representative root"],"mustProve":["The helper checks whether a node is already its own parent.","The helper recursively resolves the root.","The helper writes the compressed root back to parent[x]."],"mustNotAccept":["Returning parent[x] without resolving the full root.","A helper that never mutates parent during compression."],"equivalentVariants":["Use recursive path compression.","Use iterative path compression with an equivalent parent rewrite."],"proofSnippets":[{"id":"py-path-exists-find-function","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]"}]}},{"id":"union-roots","title":"Union by representative roots","description":"Use find on both endpoints and only connect the two roots.","commonMistakes":["Linking raw endpoints instead of roots","Continuing when both endpoints already share a root"],"hint":"Call find on both endpoint ids, then connect the returned roots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Define union so it resolves endpoint roots before linking components.","doneWhen":"Union calls find for both endpoints and links only different roots.","shouldFailWhen":"Union links raw nodes, skips find, or fails to handle already-connected endpoints.","roles":["union helper","first root","second root","parent array"],"mustProve":["Union calls the find helper for both endpoints.","Union compares roots before linking.","Union writes a parent link between roots only."],"mustNotAccept":["Assigning parent[a] = b directly without root lookup.","Linking a component to itself."],"equivalentVariants":["Resolve both roots and connect one root under the other.","Use a boolean-returning union as long as it links roots."],"proofSnippets":[{"id":"py-path-exists-union-roots","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            parent[root_b] = root_a"}]}},{"id":"union-by-rank","title":"Apply union by rank","description":"Attach the shallower root under the deeper root and increase rank on ties.","commonMistakes":["Updating rank on every union","Comparing raw endpoint ranks instead of root ranks"],"hint":"Only increase rank when both roots have the same rank.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-by-rank","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Use rank to keep the union-find forest shallow.","doneWhen":"Union compares root ranks, links the lower-rank root, and increments rank only for equal-rank roots.","shouldFailWhen":"Rank is ignored, updated for non-ties, or read from non-root nodes.","roles":["rank array","root rank comparison","tie rank increment"],"mustProve":["Root ranks are compared before linking.","The lower-rank root is attached under the higher-rank root.","The chosen root's rank increases on ties."],"mustNotAccept":["Always attaching one root regardless of rank.","Incrementing both ranks or incrementing on every merge."],"equivalentVariants":["Use union by rank.","Use union by size if represented through an equivalent rank-like auxiliary array."],"proofSnippets":[{"id":"py-path-exists-union-by-rank","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1"}]}},{"id":"process-edges","title":"Union every graph edge","description":"Scan the edge list and union both endpoints of each undirected edge.","commonMistakes":["Only processing edges that touch source","Treating edges as directed"],"hint":"Every edge tells you two nodes belong to the same component.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Merge all endpoint pairs from the edge list into union-find components.","doneWhen":"The solution loops over every edge pair and calls union on its two endpoints.","shouldFailWhen":"Some edges are skipped, endpoints are not both used, or the union helper is not called.","roles":["edge list","edge endpoints","union helper"],"mustProve":["The edge list is scanned.","Each scanned pair provides both endpoints.","The union helper receives those endpoints."],"mustNotAccept":["Checking only source-adjacent edges.","Building components without using the union helper."],"equivalentVariants":["Use `for a, b in edges` and call union on a and b.","Use indexed edge access as long as both endpoints are merged."],"proofSnippets":[{"id":"py-path-exists-process-edges","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1\n\n        for a, b in edges:\n            union(a, b)"}]}},{"id":"check-connectivity","title":"Compare source and destination roots","description":"After all unions, return whether source and destination have the same representative root.","commonMistakes":["Comparing parent[source] and parent[destination] without find","Returning true after seeing any edge"],"hint":"Use find on both query nodes after all edges have been processed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_existing_connection_verdict_by_find","scope":"check-cycle","readMode":"union-find-value-query-v1"}]},"semanticSpec":{"intent":"Answer the connectivity query by comparing final representative roots.","doneWhen":"The function returns whether find(source) equals find(destination) after processing all edges.","shouldFailWhen":"The code compares raw parents, checks before processing all edges, or ignores one query node.","roles":["source node","destination node","representative roots","boolean result"],"mustProve":["The final check calls find on source.","The final check calls find on destination.","The return compares those representative roots."],"mustNotAccept":["Returning parent[source] == parent[destination] without find.","Returning whether either node appears in any edge."],"equivalentVariants":["Return `find(source) == find(destination)` directly.","Store both roots in temporaries and compare them."],"proofSnippets":[{"id":"py-path-exists-check-connectivity","language":"python","code":"class Solution:\n    def validPath(self, n: int, edges: list[list[int]], source: int, destination: int) -> bool:\n        parent = [i for i in range(n)]\n        rank = [0] * n\n\n        def find(x: int) -> int:\n            if parent[x] != x:\n                parent[x] = find(parent[x])\n            return parent[x]\n\n        def union(a: int, b: int) -> None:\n            root_a = find(a)\n            root_b = find(b)\n            if root_a == root_b:\n                return\n            if rank[root_a] < rank[root_b]:\n                parent[root_a] = root_b\n            elif rank[root_a] > rank[root_b]:\n                parent[root_b] = root_a\n            else:\n                parent[root_b] = root_a\n                rank[root_a] += 1\n\n        for a, b in edges:\n            union(a, b)\n\n        return find(source) == find(destination)"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Union every edge, then a path exists exactly when source and destination share a root.","workspacePanel":"code","body":["Each edge merges two groups, so after processing all of them the nodes that can reach each other sit under one shared root.","The query reduces to a single root comparison: find(source) == find(destination)."],"takeaways":[{"title":"Connectivity is a shared root","body":"Two nodes are connected exactly when they climb to the same root, so a path query becomes one root comparison."},{"title":"Merge everything before you answer","body":"A later edge can be the one that bridges source and destination, so union the whole list first, then compare the roots once."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
