{"id":"number-of-connected-components-in-an-undirected-graph","title":"Number of Connected Components in an Undirected Graph","difficulty":"medium","patterns":["union-find"],"primaryConcept":"graph-union-find-connectivity","concepts":["graph-union-find-connectivity"],"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 the number of connected components in the graph.\n\nA connected component is a maximal group of nodes where every node can reach every other node through the given edges.","examples":[{"input":"n = 5, edges = [[0,1],[1,2],[3,4]]","output":"2","explanation":"Nodes 0, 1, and 2 form one component. Nodes 3 and 4 form the second component."},{"input":"n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]","output":"1","explanation":"All five nodes are connected through the chain of edges."},{"input":"n = 4, edges = []","output":"4","explanation":"With no edges, every node is its own connected component."}],"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}}}],"starterCode":"class Solution:\n    def countComponents(self, n: int, edges: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"countComponents","testCases":[{"id":"1","input":{"n":5,"edges":[[0,1],[1,2],[3,4]]},"expected":2,"description":"Two components."},{"id":"2","input":{"n":5,"edges":[[0,1],[1,2],[2,3],[3,4]]},"expected":1,"description":"One connected chain."},{"id":"3","input":{"n":4,"edges":[]},"expected":4,"description":"No edges."},{"id":"4","input":{"n":6,"edges":[[0,1],[2,3],[4,5]]},"expected":3,"description":"Three disconnected pairs."},{"id":"5","input":{"n":7,"edges":[[0,1],[1,2],[3,4],[5,6],[4,5]]},"expected":2,"description":"Two larger components."},{"id":"h1","input":{"n":1,"edges":[]},"expected":1,"description":"Single isolated node."},{"id":"h2","input":{"n":5,"edges":[[0,1],[1,2],[2,0],[3,4]]},"expected":2,"description":"A cycle still counts as one component."},{"id":"h3","input":{"n":8,"edges":[[0,1],[2,3],[3,4],[5,6]]},"expected":4,"description":"Mixed connected groups and isolated node."},{"id":"h4","input":{"n":3,"edges":[[0,1]]},"expected":2},{"id":"h5","input":{"n":6,"edges":[[0,1],[2,3],[3,4]]},"expected":3},{"id":"topup-isolated-and-chain","input":{"n":6,"edges":[[0,1],[1,2],[3,4]]},"expected":3,"description":"A chain, a pair, and an isolated node produce three components."},{"id":"topup-all-connected-star","input":{"n":5,"edges":[[0,1],[0,2],[0,3],[0,4]]},"expected":1,"description":"A star graph is one connected component."},{"id":"dense-graph-one-component","input":{"n":6,"edges":[[4,1],[2,0],[3,5],[3,1],[1,0],[2,3],[0,4],[5,2]]},"expected":1,"description":"Eight edges with several cycles join all six nodes into one component."}],"hints":[{"level":1,"content":"Every edge says two nodes belong to the same component.","revealPattern":false},{"level":2,"content":"Union the endpoints of each edge, then count how many distinct representatives remain.","revealPattern":true},{"level":3,"content":"Use path compression in find and union by rank so repeated representative lookups stay efficient.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"union-find-components","name":"Union Find components","summary":"Initialize one set per node, union every edge endpoint pair, then count representative roots.","decisionReason":"One pointer per node and a root check per edge answer connectivity directly, with no adjacency list or visited array to build first.","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,"steps":["Start every node as its own parent.","Find representatives with path compression.","Union edge endpoints by representative rank.","Count nodes that are their own representative after all unions."]},{"id":"graph-traversal-components","name":"DFS/BFS components","summary":"Build adjacency lists and launch a traversal from every unvisited node.","decisionReason":"This counts components too, but it first turns the edges into an adjacency list and carries a visited array, state the union pointers never need.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time and uses O(n + e) space."],"isOptimal":false,"steps":["Build an adjacency list.","Start a traversal from each unvisited node.","Increment the component count for every fresh traversal."]}]},"codingCheckpoints":[{"id":"init-arrays","title":"Initialize parent and rank arrays","description":"Start every node as its own representative and create rank state for balanced unions.","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":["Forgetting to initialize every node as its own parent","Creating a rank array with a different length"],"hint":"Parent starts as [0, 1, 2, ...], and rank starts at zero for every node.","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-components-init-parent-rank","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\n        parent = list(range(n))\n        rank = [0] * n"}]}},{"id":"find-function","title":"Implement path-compressed find","description":"Write find so each lookup returns the representative and compresses the path on the way back.","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 immediate parent without compressing","Updating parent with the wrong index"],"hint":"If x is not its own parent, recursively find the root and store it back into parent[x].","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-components-path-compression","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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":"Union representatives, not raw nodes","description":"Find both representatives and link one root under the other only when they differ.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Assigning parent[y] = x without finding roots","Not checking whether the roots are already equal"],"hint":"Always call find on both endpoints before writing to parent.","semanticSpec":{"intent":"Merge sets by comparing and linking their representatives.","doneWhen":"union finds both roots, skips equal 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 already-equal roots as if they were separate."],"equivalentVariants":["Return a boolean when a merge happens.","Return nothing and just skip equal roots."],"proofSnippets":[{"id":"py-components-union-by-root","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\n            parent[root_y] = root_x"}]}},{"id":"union-by-rank","title":"Apply union by rank","description":"Use rank to attach the shallower tree under the deeper tree and increase rank on ties.","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 ranks but never writing the chosen parent","Forgetting to increase rank on a tie"],"hint":"Compare rank[root_x] and rank[root_y], then only increase rank when the ranks were equal.","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-components-ranked-union","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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":"process-edges","title":"Union every edge","description":"Scan the edge list and union each pair of endpoints.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Processing only the first edge","Calling union with a constant pair instead of the current edge endpoints"],"hint":"Each edge contributes exactly one union call between its two endpoints.","semanticSpec":{"intent":"Apply the union helper to every pair in the edge sequence.","doneWhen":"The code loops over edges and calls union with the current edge endpoints.","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."],"mustNotAccept":["A single hard-coded union call.","A loop that never calls union."],"equivalentVariants":["Destructure each edge into u and v.","Index edge[0] and edge[1] when calling union."],"proofSnippets":[{"id":"py-components-union-each-edge","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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        for u, v in edges:\n            union(u, v)"}]}},{"id":"count-components","title":"Return the component count","description":"After all unions, count how many nodes are their own representative and return that total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_distinct_root_count","scope":"count-provinces","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning n without applying unions","Counting parent values without calling find first"],"hint":"Compress each node to its representative, count roots, then return the component total.","semanticSpec":{"intent":"Derive the final component count from representative roots after all edge merges.","doneWhen":"The terminal result counts representative roots using find after the union pass and returns the component count.","shouldFailWhen":"The code returns the original node count or counts stale parent entries without representative lookup.","roles":["find helper","representative roots","component count"],"mustProve":["Every node is resolved through find.","The returned count is based on representative roots."],"mustNotAccept":["Returning n directly.","Counting parent entries without root lookup."],"equivalentVariants":["Count nodes whose representative is themselves.","Build a set of find(i) values and return its size."],"proofSnippets":[{"id":"py-components-count-roots","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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        for u, v in edges:\n            union(u, v)\n        components = 0\n        for i in range(n):\n            if find(i) == i:\n                components += 1\n        return components"}]}}],"slides":[{"id":"read-the-signal","chapter":"The graph","kind":"info","eyebrow":"Read the problem","title":"How many separate groups of nodes?","workspacePanel":"problem","body":["You get n nodes labeled 0 to n-1 and a list of undirected edges. A connected component is a group of nodes that can all reach each other by walking along edges. Count the components.","Components chain through edges: 0 reaches 2 by way of 1 even though no edge links 0 and 2 directly."]},{"id":"flood-baseline","chapter":"The slow way","kind":"info","eyebrow":"The obvious way","title":"Flood out from each fresh node","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4]}}}]},"body":["One way that works: build a neighbor list for every node, then walk the nodes in order. Each time you reach a node you have not seen, flood from it with DFS or BFS, marking everything reachable as seen.","Every fresh flood you launch is one more component, so the number of floods is the answer."]},{"id":"flood-cost","chapter":"The slow way","kind":"case-probe","eyebrow":"Weigh the cost","title":"What does the flood approach make you build and carry first?","summary":"The same answer the merges give, but the flood needs a setup before it can start.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"input-graph","state":{"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[1,2],[3,4]]}}}]},"options":[{"id":"adj-and-visited","label":"A full neighbor list for every node and a separate seen marker","rationale":"The flood reads neighbors, so you first turn the edge list into an adjacency structure and keep a seen array to avoid revisiting. That is extra state the edges already imply.","isCorrect":true},{"id":"sorted-edges","label":"The edges sorted by node id","rationale":"Order does not matter for connectivity, so sorting buys nothing. The work comes from the neighbor list and the seen tracking.","isCorrect":false},{"id":"nothing","label":"Nothing, you can flood straight off the edge list","rationale":"Walking neighbors off a raw edge list rescans every edge per node. To flood efficiently you build adjacency first, and you still carry a seen array.","isCorrect":false}],"answer":"A neighbor list and a seen marker. The flood reaches a node through its neighbors, so you build adjacency up front and track which nodes are already visited."},{"id":"merge-idea","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Read the edges as merges","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4]}}}]},"body":["Each edge says two nodes belong to the same group. Instead of flooding, you can act on that directly: give every node one pointer, and to start, point each node at itself so every node is its own group of one.","An edge then merges the two groups its endpoints sit in."]},{"id":"count-from-merges","chapter":"The idea","kind":"case-probe","eyebrow":"Find the count","title":"You start with n groups and merge along edges. What is the component count?","summary":"Five nodes begin as five groups, and each edge merges the two groups its endpoints belong to.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,0,3,4]}}}]},"options":[{"id":"n-minus-merges","label":"n minus one for every edge that joins two different groups","rationale":"Each merge of two distinct groups turns two groups into one, dropping the count by one. An edge whose endpoints already share a group merges nothing and leaves the count alone.","isCorrect":true},{"id":"n-minus-edges","label":"n minus the number of edges","rationale":"That overcounts: an edge between two nodes already in the same group joins nothing, so it must not drop the count. Only merges of different groups do.","isCorrect":false},{"id":"edges","label":"The number of edges","rationale":"Edges are not groups. A group of three nodes can be wired with two or three edges, so edges do not count components. The surviving groups do.","isCorrect":false}],"answer":"Start at n, and subtract one for every edge that joins two different groups. An edge inside one group merges nothing and leaves the count unchanged."},{"id":"same-group-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"When are two nodes in the same component?","summary":"Following a node’s pointers leads up to the one node that points at itself, its root.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,1,3,4]}}}]},"options":[{"id":"same-root","label":"When they climb to the same root","rationale":"Following pointers from either node ends at its group root, so a shared root is exactly a shared component.","isCorrect":true},{"id":"direct-edge","label":"When an edge links them directly","rationale":"A component chains through any sequence of edges, so two nodes can share one with no direct edge between them.","isCorrect":false},{"id":"parent","label":"When one is the other’s parent","rationale":"A direct pointer is one step. Nodes deep in one group need not point at each other, yet still climb to one root.","isCorrect":false}],"answer":"When they climb to the same root. Following pointers from either node lands on its group root, so a shared root is exactly a shared component."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which structure should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,0,3,3]}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Merge each edge, then count roots","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4,5]}}}]},"body":["Six nodes start as six roots. Walk the edge list, and for each edge climb both endpoints to their roots and link one root under the other.","When two endpoints already share a root, linking them changes nothing and the count holds. After every edge, count the nodes still pointing at themselves."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the merges","title":"Trace the merging groups","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"merge-01","state":{"graph":{"parent":[0,0,2,3,4,5],"current":1,"highlighted":[0],"activeEdges":[[1,0]]}}},{"id":"merge-12","state":{"graph":{"parent":[0,0,0,3,4,5],"current":2,"highlighted":[0],"activeEdges":[[2,0]]}}},{"id":"redundant-02","state":{"graph":{"parent":[0,0,0,3,4,5],"current":0,"highlighted":[2]}}},{"id":"merge-34","state":{"graph":{"parent":[0,0,0,3,3,5],"current":4,"highlighted":[3],"activeEdges":[[4,3]]}}},{"id":"count","state":{"graph":{"parent":[0,0,0,3,3,5]}}}]},"beats":[{"id":"merge-01","title":"Edge [0, 1] joins two roots. What happens to the count?","summary":"Six nodes, six roots. Nodes 0 and 1 are each their own root.","prompt":"Edge [0, 1] is processed.","options":[{"id":"drop-to-5","label":"Node 1 points to 0, and the count drops to 5","rationale":"Their roots are 0 and 1, two different groups. Linking 1 under 0 merges them into one, so six groups become five.","isCorrect":true},{"id":"no-change","label":"Nothing changes, they were already together","rationale":"Each started as its own root, so this edge is the first thing that joins them. It does drop the count.","isCorrect":false},{"id":"new-root","label":"A brand-new node becomes the parent of both","rationale":"No new node appears. One of the two existing roots becomes the parent of the other.","isCorrect":false}],"answer":"Node 1 points to 0, merging two roots into one. The count drops from 6 to 5."},{"id":"merge-12","title":"Edge [1, 2] arrives. Node 1 already sits under root 0. What links?","summary":"Root 0 holds {0, 1}; node 2 is still its own root.","prompt":"Edge [1, 2] is processed.","options":[{"id":"drop-to-4","label":"Node 2 points to root 0, and the count drops to 4","rationale":"Climbing 1 reaches root 0, and 2’s root is 2. The roots differ, so linking 2 under 0 pulls 2 into {0, 1}, leaving {0, 1, 2}. Count falls to 4.","isCorrect":true},{"id":"one-to-two","label":"Node 1 points to 2, leaving 0 behind","rationale":"Node 1 already climbs to root 0. Link root 2 under root 0 so the whole existing group stays connected.","isCorrect":false},{"id":"hold","label":"The count holds, since 1 is already placed","rationale":"Node 2 was a separate root, so this edge merges two different groups and the count does drop.","isCorrect":false}],"answer":"Node 2 points to root 0. Nodes {0, 1, 2} now share root 0, and the count drops from 5 to 4."},{"id":"redundant-02","title":"Edge [0, 2] arrives. Both already climb to root 0. What is the count now?","summary":"Nodes 0 and 2 already share root 0.","prompt":"Edge [0, 2] is processed.","options":[{"id":"holds-at-4","label":"The count holds at 4","rationale":"Both endpoints climb to the same root 0, so there is nothing to merge. A redundant edge inside one group leaves the count unchanged.","isCorrect":true},{"id":"drop-to-3","label":"It drops to 3","rationale":"Dropping here would be the trap: the endpoints are already one group, so no merge happens. Only edges that join two different roots may drop the count.","isCorrect":false},{"id":"splits","label":"The group splits back apart","rationale":"Edges only ever merge groups. An edge inside a group does nothing at all, it never splits one.","isCorrect":false}],"answer":"The count holds at 4. Both endpoints already climb to root 0, so this edge merges nothing."},{"id":"merge-34","title":"Edge [3, 4] arrives, with no link to the first group. What forms?","summary":"Nodes 3 and 4 are each their own root, and node 5 has no edge at all.","prompt":"Edge [3, 4] is processed.","options":[{"id":"drop-to-3","label":"A second group forms, and the count drops to 3","rationale":"Roots 3 and 4 differ from each other and from the first group, so they merge into {3, 4}. With {0,1,2}, {3,4}, and the lone node 5, three groups remain.","isCorrect":true},{"id":"join-first","label":"Nodes 3 and 4 join the group with 0, 1, 2","rationale":"No edge links them to that group, so they stay separate from {0, 1, 2}.","isCorrect":false},{"id":"to-2","label":"The count drops to 2","rationale":"This edge merges only 3 and 4. Node 5 still has no edge, so it remains its own group and the count lands at 3, not 2.","isCorrect":false}],"answer":"Nodes 3 and 4 merge into a second group, and the count drops to 3: {0,1,2}, {3,4}, and the lone node 5."},{"id":"count","title":"After every edge is processed, how many roots remain?","prompt":"Read the nodes still pointing at themselves off the forest.","options":[{"id":"three","label":"3, one per group","rationale":"Nodes 0, 3, and 5 are the only ones still pointing at themselves, so three components remain.","isCorrect":true},{"id":"six","label":"6, one per node","rationale":"The merges collapsed the forest onto roots 0, 3, and 5. Count those roots to get the components.","isCorrect":false},{"id":"two","label":"2, the two edge groups","rationale":"Node 5 never appeared in an edge, so it stays its own group. That gives three roots.","isCorrect":false}],"answer":"Three. Nodes 0, 3, and 5 are still their own root, so the forest holds three components."}]},{"id":"blind-decrement-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you just subtract one for every edge?","summary":"Starting the count at n and dropping it by one on each edge looks right, and it holds up while every edge joins two fresh groups. The trouble shows up once an edge lands inside a group that is already merged. Watch a triangle of three nodes.","workspacePanel":"trace","pitfall":"The count below starts at n and subtracts one for every edge, with no check for whether the endpoints already share a group.","whyItMatters":"An edge inside an existing group merges nothing, so subtracting on it overcounts the merges and undershoots the real answer. Compare the two roots first, and drop the count only when they differ.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"count = n\nfor u, v in edges:\n    count = count - 1\nreturn count","steps":[{"id":"edge-01","title":"Edge [0, 1] drops the count to 2","codeLine":3,"summary":"Three nodes, count starts at 3. Edge [0, 1] joins two fresh groups, so dropping to 2 is correct so far.","state":{"graph":{"parent":[0,0,2],"current":1,"highlighted":[0],"activeEdges":[[1,0]]}}},{"id":"edge-12","title":"Edge [1, 2] drops the count to 1","codeLine":3,"summary":"Edge [1, 2] pulls node 2 into the group rooted at 0. Two fresh roots merged, so dropping to 1 is still correct.","state":{"graph":{"parent":[0,0,0],"current":2,"highlighted":[0],"activeEdges":[[2,0]]}}},{"id":"edge-02","title":"Edge [0, 2] drops the count to 0","codeLine":3,"summary":"Nodes 0 and 2 already climb to the same root, so this edge merges nothing. The blind subtract drops the count anyway, to 0.","state":{"graph":{"parent":[0,0,0],"current":0,"highlighted":[2]}}},{"id":"wrong-answer","title":"It returns 0","codeLine":4,"summary":"All three nodes are one connected component, so the real answer is 1. The blind subtract returned 0.","state":{"graph":{"parent":[0,0,0]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let count = n;\nfor (const [u, v] of edges) {\n    count = count - 1;\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5},"statementBundles":{"3":{"startLine":3,"endLine":4}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let count = n;\nfor (const [u, v] of edges) {\n    count = count - 1;\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5},"statementBundles":{"3":{"startLine":3,"endLine":4}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int count = n;\nfor (List<Integer> edge : edges) {\n    int u = edge.get(0);\n    int v = edge.get(1);\n    count = count - 1;\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":5,"4":7},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int count = n;\nforeach (var item in edges) {\n    int u = item[0];\n    int v = item[1];\n    count = count - 1;\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":5,"4":7},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int count = n;\nfor (vector<int> item : edges) {\n    int u = item[0];\n    int v = item[1];\n    count = count - 1;\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":5,"4":7},"statementBundles":{"2":{"startLine":2,"endLine":4},"3":{"startLine":5,"endLine":6}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3]}}}]},"body":["Linking edges by their roots and counting the survivors named the components in the sample, where a redundant edge changed nothing.","Before coding it, push on the inputs that stress how the count is seeded and which nodes a merge can reach."]},{"id":"no-edges-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if there are no edges at all?","summary":"n = 4, and the edge list is empty.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3]}}}]},"options":[{"id":"four","label":"4, one component per node","rationale":"With nothing to merge, every node stays its own root and its own group, so the count equals n. This is why the parent array is seeded for all n nodes up front.","isCorrect":true},{"id":"zero","label":"0, there is nothing connected","rationale":"A lone node is still a component by itself. With no edges there are n of them, not zero.","isCorrect":false},{"id":"one","label":"1, they form a single empty group","rationale":"Nodes with no edge between them do not share a component. Each is alone, giving n components.","isCorrect":false}],"answer":"4. No edge ever merges anything, so every node stays its own root, one component each."},{"id":"isolated-node-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A node sits in no edge while the others merge. Does it count?","summary":"n = 3 with the single edge [0, 1], so node 2 never appears in any edge.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,2]}}}]},"options":[{"id":"two","label":"2, the merged pair plus the lone node","rationale":"Edge [0, 1] merges 0 and 1 into one group, and node 2 still points at itself. A node absent from every edge is a component of one, so two roots remain.","isCorrect":true},{"id":"one","label":"1, only nodes touched by an edge count","rationale":"Seeding parent for all n nodes is exactly what keeps node 2 in the count. It never merges, so it stays its own root and its own component.","isCorrect":false},{"id":"three","label":"3, the edge did not change anything","rationale":"Edge [0, 1] joins two different roots, so it does drop the count by one. Three would mean the merge never happened.","isCorrect":false}],"answer":"2. Edge [0, 1] merges that pair into one root, and node 2, in no edge, stays its own root, so two components remain."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Build the merge and count the roots","summary":"Merge by roots, and drop the count only when the two roots differ.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4,5]}}}]},"body":["Start each node as its own parent, with a find that climbs to a root and flattens what it passes. For every edge, climb both endpoints to their roots and link one root under the other, breaking ties by rank.","At the end, count the nodes that are still their own parent."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the component merge","eyebrow":"Code the rule","summary":"Build the parent and rank arrays, merge endpoints by their roots, ignore edges already inside one component, and return the number of roots left.","workspacePanel":"code","checkpoints":[{"id":"init-arrays","title":"Initialize parent and rank arrays","description":"Start every node as its own representative and create rank state for balanced unions.","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":["Forgetting to initialize every node as its own parent","Creating a rank array with a different length"],"hint":"Parent starts as [0, 1, 2, ...], and rank starts at zero for every node.","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-components-init-parent-rank","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\n        parent = list(range(n))\n        rank = [0] * n"}]}},{"id":"find-function","title":"Implement path-compressed find","description":"Write find so each lookup returns the representative and compresses the path on the way back.","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 immediate parent without compressing","Updating parent with the wrong index"],"hint":"If x is not its own parent, recursively find the root and store it back into parent[x].","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-components-path-compression","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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":"Union representatives, not raw nodes","description":"Find both representatives and link one root under the other only when they differ.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Assigning parent[y] = x without finding roots","Not checking whether the roots are already equal"],"hint":"Always call find on both endpoints before writing to parent.","semanticSpec":{"intent":"Merge sets by comparing and linking their representatives.","doneWhen":"union finds both roots, skips equal 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 already-equal roots as if they were separate."],"equivalentVariants":["Return a boolean when a merge happens.","Return nothing and just skip equal roots."],"proofSnippets":[{"id":"py-components-union-by-root","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\n            parent[root_y] = root_x"}]}},{"id":"union-by-rank","title":"Apply union by rank","description":"Use rank to attach the shallower tree under the deeper tree and increase rank on ties.","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 ranks but never writing the chosen parent","Forgetting to increase rank on a tie"],"hint":"Compare rank[root_x] and rank[root_y], then only increase rank when the ranks were equal.","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-components-ranked-union","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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":"process-edges","title":"Union every edge","description":"Scan the edge list and union each pair of endpoints.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Processing only the first edge","Calling union with a constant pair instead of the current edge endpoints"],"hint":"Each edge contributes exactly one union call between its two endpoints.","semanticSpec":{"intent":"Apply the union helper to every pair in the edge sequence.","doneWhen":"The code loops over edges and calls union with the current edge endpoints.","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."],"mustNotAccept":["A single hard-coded union call.","A loop that never calls union."],"equivalentVariants":["Destructure each edge into u and v.","Index edge[0] and edge[1] when calling union."],"proofSnippets":[{"id":"py-components-union-each-edge","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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        for u, v in edges:\n            union(u, v)"}]}},{"id":"count-components","title":"Return the component count","description":"After all unions, count how many nodes are their own representative and return that total.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"returns_distinct_root_count","scope":"count-provinces","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning n without applying unions","Counting parent values without calling find first"],"hint":"Compress each node to its representative, count roots, then return the component total.","semanticSpec":{"intent":"Derive the final component count from representative roots after all edge merges.","doneWhen":"The terminal result counts representative roots using find after the union pass and returns the component count.","shouldFailWhen":"The code returns the original node count or counts stale parent entries without representative lookup.","roles":["find helper","representative roots","component count"],"mustProve":["Every node is resolved through find.","The returned count is based on representative roots."],"mustNotAccept":["Returning n directly.","Counting parent entries without root lookup."],"equivalentVariants":["Count nodes whose representative is themselves.","Build a set of find(i) values and return its size."],"proofSnippets":[{"id":"py-components-count-roots","language":"python","code":"class Solution:\n    def countComponents(self, n, edges):\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\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        for u, v in edges:\n            union(u, v)\n        components = 0\n        for i in range(n):\n            if find(i) == i:\n                components += 1\n        return components"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Start at n components and drop one for every edge that merges two different groups; the surviving roots are the answer.","workspacePanel":"code","body":["Nodes in one component are exactly those that union into one group, so merging each edge collapses every component down to a single root.","Once every edge is processed, counting the roots counts the components, and an edge inside an existing group simply changes nothing."],"takeaways":[{"title":"A component is one root","body":"Merging by root means every node in a group climbs to the same representative, so distinct roots and distinct components are the same count."},{"title":"Only real merges drop the count","body":"Comparing the two roots before linking keeps a redundant edge from subtracting, so the count tracks groups and not edges."},{"title":"Near-linear, because the trees stay flat","body":"Path compression and union by rank keep each find and union nearly constant, so n nodes and e edges cost about O((n + e) * α(n)) time and O(n) space, below the flood’s adjacency overhead."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
