{"id":"number-of-operations-to-make-network-connected","title":"Number of Operations to Make Network Connected","difficulty":"medium","patterns":["union-find"],"primaryConcept":"graph-union-find-connectivity","concepts":["graph-union-find-connectivity"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"connections","sizeMetric":"nodes-plus-edges","secondaryParams":{"n":{"strategy":"scale-with-primary"}},"constraints":["mixed-components"]},"description":"There are `n` computers labeled from `0` to `n - 1` connected by ethernet cables. You are given `connections`, where `connections[i] = [a, b]` means computer `a` is directly connected to computer `b`.\n\nYou can remove an existing cable and reconnect it between any two disconnected computers. Return the minimum number of operations needed to make all computers connected. Return `-1` if it is impossible.","examples":[{"input":"n = 4, connections = [[0,1],[0,2],[1,2]]","output":"1","explanation":"One redundant cable can be moved to connect computer 3."},{"input":"n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]","output":"2","explanation":"There are three connected components, so two operations are needed."},{"input":"n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]","output":"-1","explanation":"At least n - 1 cables are required to connect n computers, but only four cables are available."}],"constraints":[{"id":"1-n-100000","text":"1 <= n <= 100000","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":100000}},{"id":"0-len-connections-min-n-n-1-2-100000","text":"0 <= len(connections) <= min(n * (n - 1) / 2, 100000)"},{"id":"connections-i-length-2","text":"len(connections[i]) == 2","check":{"kind":"shape","target":"connections","shape":"tupleArray","tupleLength":2}},{"id":"0-connections-i-0-connections-i-1-n","text":"0 <= connections[i][0], connections[i][1] < n","check":[{"kind":"valueRange","target":"connections","selector":"tupleItemsAtIndex","index":0,"min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"connections","selector":"tupleItemsAtIndex","index":1,"min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"connections-i-0-connections-i-1","text":"connections[i][0] != connections[i][1]","check":{"kind":"compare","target":"connections","left":{"field":0},"op":"!=","right":{"field":1}}},{"id":"there-are-no-repeated-connections","text":"There are no repeated connections"}],"starterCode":"class Solution:\n    def makeConnected(self, n: int, connections: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"makeConnected","testCases":[{"id":"1","input":{"n":4,"connections":[[0,1],[0,2],[1,2]]},"expected":1,"description":"One isolated node can be connected using one redundant cable."},{"id":"2","input":{"n":6,"connections":[[0,1],[0,2],[0,3],[1,2],[1,3]]},"expected":2,"description":"Three components require two cable moves."},{"id":"3","input":{"n":6,"connections":[[0,1],[0,2],[0,3],[1,2]]},"expected":-1,"description":"Not enough total cables."},{"id":"4","input":{"n":5,"connections":[[0,1],[1,2],[2,3],[3,4]]},"expected":0,"description":"Already connected as a chain."},{"id":"5","input":{"n":1,"connections":[]},"expected":0,"description":"A single computer is already connected."},{"id":"6","input":{"n":7,"connections":[[0,1],[1,2],[2,0],[3,4],[4,5],[5,3]]},"expected":2,"description":"Two cyclic components plus an isolated computer."},{"id":"h1","input":{"n":2,"connections":[]},"expected":-1,"description":"Two computers with no cable cannot be connected."},{"id":"h2","input":{"n":8,"connections":[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,4]]},"expected":2,"description":"Two connected groups and one isolated computer with enough spare cables."},{"id":"h3","input":{"n":4,"connections":[[0,1],[2,3],[1,2]]},"expected":0,"description":"Exactly n - 1 cables and connected."},{"id":"h4","input":{"n":6,"connections":[[0,1],[1,2],[2,0],[3,4],[4,5]]},"description":"Two components with one redundant cable need a single move.","expected":1},{"id":"topup-not-enough-cables","input":{"n":5,"connections":[[0,1],[2,3]]},"expected":-1,"description":"Too few cables cannot connect all components."},{"id":"topup-extra-cable-connects-three-components","input":{"n":6,"connections":[[0,1],[0,2],[3,4],[2,1],[4,5]]},"expected":1,"description":"An extra cable can be reassigned to connect remaining components."},{"id":"already-connected-larger-index-first","input":{"n":3,"connections":[[0,2],[2,1]]},"expected":0,"description":"The cables already connect every computer, and the second cable lists the larger index first."}],"hints":[{"level":1,"content":"A connected network with `n` computers needs at least `n - 1` cables.","revealPattern":false},{"level":2,"content":"If there are enough cables, count how many connected components the existing network has.","revealPattern":true},{"level":3,"content":"Use union-find to merge connected computers. If there are `c` components, connecting them takes `c - 1` operations.","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 groups","summary":"Reject inputs with fewer than n-1 cables, start one set per computer, union every cable's endpoints, then return the surviving root count minus one.","decisionReason":"One pointer per computer and a root check per cable 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":["Return -1 if fewer than n-1 cables exist.","Start every computer as its own parent.","Find representatives with path compression.","Union cable endpoints by representative rank.","Return the count of own-parent roots minus one."]},{"id":"dfs-components","name":"DFS/BFS groups","summary":"Build adjacency lists, flood from every unvisited computer to count groups, then return that count minus one.","decisionReason":"This counts groups too, but it first turns the cables 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.","Flood from each unvisited computer.","Return the group count minus one if enough cables exist."]}]},"codingCheckpoints":[{"id":"init-arrays","title":"Initialize parent and rank","description":"Create union-find parent and rank arrays for all computers.","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":["Only initializing parent for computers that appear in a cable","Forgetting the rank array"],"hint":"Every computer starts as its own component.","semanticSpec":{"intent":"Initialize disjoint-set state for all computers.","doneWhen":"Parent and rank arrays are initialized across the node range.","shouldFailWhen":"Some computers have no parent entry or rank state is missing.","roles":["parent array","rank array","computer labels"],"mustProve":["Each node starts as its own parent.","Rank or size state is initialized for union balancing."],"mustNotAccept":["Only tracking nodes that appear in edges."]}},{"id":"find-function","title":"Compress paths in find","description":"Implement `find` so it follows parents to the root and compresses the path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning only the immediate parent","Not writing the compressed root back"],"hint":"If a node is not its own parent, recursively find the root and store it.","semanticSpec":{"intent":"Resolve the representative root while shortening future paths.","doneWhen":"The find helper recursively follows parents and writes the representative back.","shouldFailWhen":"Find does not compress or returns an unresolved parent.","roles":["find helper","parent array","representative root"],"mustProve":["Find walks parent links until a root is reached.","Find stores the representative root for compression."],"mustNotAccept":["A find function with no parent-link recursion or loop."]}},{"id":"union-function","title":"Union by representatives","description":"Merge two computers by first finding their component roots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Linking raw nodes instead of roots","Merging even when the roots are already equal"],"hint":"Call find on both endpoints before writing any parent link.","semanticSpec":{"intent":"Merge components by representative roots.","doneWhen":"Union finds both roots and links one root to the other if they differ.","shouldFailWhen":"Union links non-root nodes directly.","roles":["union helper","root representatives","parent links"],"mustProve":["Union uses find results for both endpoints.","Union writes a parent link between roots."],"mustNotAccept":["Directly setting `parent[x] = y` without root lookup."]}},{"id":"union-by-rank","title":"Use rank when linking roots","description":"Attach the shallower root under the deeper root and update rank on ties.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Ignoring rank completely","Forgetting to increment rank on a tie"],"hint":"Compare root ranks before choosing which parent pointer to update.","semanticSpec":{"intent":"Keep union-find trees shallow with a rank heuristic.","doneWhen":"Union compares ranks and increments rank when equal-ranked roots merge.","shouldFailWhen":"Union always links the second root under the first without rank logic.","roles":["rank array","root representatives","parent link"],"mustProve":["Rank controls which root becomes parent.","Rank is updated when equal ranks are merged."],"mustNotAccept":["No rank or size heuristic."]}},{"id":"process-connections","title":"Union every cable","description":"Scan the connection list and union both endpoints of each cable.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Skipping duplicate-looking but valid edges","Only processing one endpoint"],"hint":"Each connection is a pair of computers to merge.","semanticSpec":{"intent":"Apply union-find merging to every given cable.","doneWhen":"The solution loops through the edge list and calls union on each pair.","shouldFailWhen":"Connections are not scanned or union is not called for them.","roles":["connection pair","union helper"],"mustProve":["The edge list is scanned.","Each pair can trigger a union operation."],"mustNotAccept":["Counting edges without merging components."]}},{"id":"count-components","title":"Count connected components","description":"After all unions, count how many distinct representative roots remain.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"counts_distinct_roots","scope":"count-provinces","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Counting parent values without compressing roots","Counting cables instead of components"],"hint":"A computer starts a component only if it is its own representative after find.","semanticSpec":{"intent":"Count the remaining disjoint-set representatives.","doneWhen":"The solution calls find over the node range and counts representative roots.","shouldFailWhen":"It counts raw parents or edge groups without resolving roots.","roles":["component count","find helper","representative roots"],"mustProve":["The final count is based on distinct roots."],"mustNotAccept":["Returning the number of edges or redundant cables."]}},{"id":"return-operations","title":"Return required operations","description":"Return the numeric number of cable moves needed after component counting.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the component count directly","Returning a boolean connectivity result"],"hint":"Connecting `components` groups needs `components - 1` operations.","semanticSpec":{"intent":"Return the final numeric operation count.","doneWhen":"The terminal return is a numeric answer derived from the connected component count.","shouldFailWhen":"The function returns the parent array, a boolean, or the raw edge count.","roles":["component count","operation count","terminal return"],"mustProve":["The function returns a numeric answer after component counting."],"mustNotAccept":["Returning non-answer state."]}}],"slides":[{"id":"read-the-problem","chapter":"The network","kind":"info","eyebrow":"Read the problem","title":"Fewest cable moves to connect every computer","workspacePanel":"problem","body":["You have n computers labeled 0 to n-1 and a list of cables, each joining two computers. One move unplugs a cable from where it is and plugs it back between any two computers you choose. Return the fewest moves that leave every computer reachable from every other, or -1 if no sequence of moves can do it.","A cable between two computers already in the same group is spare wire: it can be unplugged and reused without disconnecting anything."]},{"id":"flood-baseline","chapter":"The first idea","kind":"info","eyebrow":"The obvious way","title":"Flood each group to count them","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3]}}}]},"body":["One way that works: build a neighbor list for every computer, then walk the computers in order. Each time you reach one you have not seen, flood from it with DFS or BFS and mark everything reachable as seen. Every fresh flood is one more group.","This genuinely counts the groups. The question is what it makes you build first, since the cables arrive as a flat list of pairs but a flood walks a computer's neighbors."]},{"id":"flood-cost","chapter":"The first idea","kind":"case-probe","eyebrow":"Weigh the cost","title":"What does the flood make you build before it can start?","summary":"The cables arrive as a flat list of pairs, but a flood walks a computer's neighbors.","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 neighbor list for every computer and a separate seen marker","rationale":"The flood reaches a computer through its neighbors, so you first turn the cable list into an adjacency structure and carry a seen array to avoid revisiting. That is extra state the cables already imply.","isCorrect":true},{"id":"sorted-cables","label":"The cables sorted by computer id","rationale":"Order has no bearing on which computers end up connected, 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 cable list","rationale":"Walking neighbors off a raw cable list rescans every cable per computer. To flood without that blowup 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 computer through its neighbors, so you build adjacency up front and track which computers are already visited."},{"id":"merge-idea","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Read each cable as a merge","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3]}}}]},"body":["Each cable says two computers belong to the same group. Instead of flooding, act on that directly: give every computer one pointer, and to start, point each computer at itself so every one is its own group of one.","A cable then merges the two groups its endpoints sit in. A cable whose endpoints already share a group merges nothing, and that is exactly the spare wire you can move."]},{"id":"count-from-merges","chapter":"The idea","kind":"case-probe","eyebrow":"Find the count","title":"Start with n groups and merge along cables. How many groups remain?","summary":"Four computers begin as four groups, and each cable 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]}}}]},"options":[{"id":"n-minus-merges","label":"n minus one for every cable that joins two different groups","rationale":"Each merge of two distinct groups turns two groups into one, dropping the count by one. A cable whose endpoints already share a group merges nothing and leaves the count alone.","isCorrect":true},{"id":"n-minus-cables","label":"n minus the number of cables","rationale":"That overcounts: a cable between two computers already in one group joins nothing, so it must not drop the count. Only merges of different groups do.","isCorrect":false},{"id":"cables","label":"The number of cables","rationale":"Cables are not groups. A group of three computers can be wired with two or three cables, so cables do not count groups. The surviving groups do.","isCorrect":false}],"answer":"Start at n, and subtract one for every cable that joins two different groups. A cable inside one group merges nothing and leaves the count unchanged."},{"id":"moves-from-groups","chapter":"The idea","kind":"case-probe","eyebrow":"Find the moves","title":"After merging leaves g groups, how many moves connect them?","summary":"The merges left g separate components. A move can bridge two components.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,0,3,4]}}}]},"options":[{"id":"g-minus-1","label":"g - 1, one spare cable bridges each gap between groups","rationale":"Linking g groups into one closes g-1 gaps, and each gap needs one cable. The redundant cables sitting inside groups are exactly the spares you move to close them, so g-1 moves suffice.","isCorrect":true},{"id":"g","label":"g, one move per group","rationale":"The last group needs no bridge to itself. Connecting g groups closes g-1 gaps, so the final group is reached once the others are joined.","isCorrect":false},{"id":"count-redundant","label":"However many redundant cables exist","rationale":"The number of spares does not set the answer; the number of gaps does. As long as enough spares exist, g-1 moves close every gap no matter how many extras are lying around.","isCorrect":false}],"answer":"g - 1. Linking g groups closes g-1 gaps, and a redundant cable inside any group is the spare you move to close one."},{"id":"feasibility","chapter":"The idea","kind":"case-probe","eyebrow":"Find the limit","title":"When is connecting every computer impossible?","summary":"Closing every gap needs one spare cable per gap. n computers in g groups have g-1 gaps to close.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"input-graph","state":{"graph":{"nodes":[0,1,2,3,4],"edges":[[0,1],[2,3]]}}}]},"options":[{"id":"too-few-cables","label":"When there are fewer than n-1 cables in total","rationale":"A connected network of n computers needs at least n-1 cables. With fewer than that, even reusing every cable as a spare cannot close all the gaps, so no sequence of moves connects everything.","isCorrect":true},{"id":"any-isolated","label":"Whenever a computer has no cable","rationale":"A lone computer is fine as long as a spare cable exists to reach it. It is impossible only when the total cable count itself falls below n-1.","isCorrect":false},{"id":"never","label":"Never, you can always rewire enough","rationale":"Moving a cable never creates a new one. With fewer than n-1 cables there are not enough wires to span n computers, so some pair stays unreachable.","isCorrect":false}],"answer":"When fewer than n-1 cables exist. Spanning n computers needs at least n-1 cables, and a move only relocates a cable, never adds one, so below that it is impossible."},{"id":"same-group-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"When are two computers in the same group?","summary":"Following a computer's pointers leads up to the one computer 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 computer ends at its group root, so a shared root is exactly a shared group.","isCorrect":true},{"id":"direct-cable","label":"When a cable links them directly","rationale":"A group chains through any sequence of cables, so two computers can share one with no direct cable between them.","isCorrect":false},{"id":"parent","label":"When one is the other's parent","rationale":"A direct pointer is one step. Computers 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 computer lands on its group root, so a shared root is exactly a shared group."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","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 cable, count the groups, subtract one","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4,5]}}}]},"body":["Six computers start as six roots, and the cable count is 5, which clears the n-1 feasibility bar. Walk the cables, and for each one climb both endpoints to their roots and link one root under the other.","When two endpoints already share a root, linking them changes nothing. After every cable, the groups that remain are the roots still pointing at themselves, and the answer is that count minus one."]},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","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-02","state":{"graph":{"parent":[0,0,0,3,4,5],"current":2,"highlighted":[0],"activeEdges":[[2,0]]}}},{"id":"merge-34","state":{"graph":{"parent":[0,0,0,3,3,5],"current":4,"highlighted":[3],"activeEdges":[[4,3]]}}},{"id":"redundant-21","state":{"graph":{"parent":[0,0,0,3,3,5],"current":2,"highlighted":[1]}}},{"id":"merge-45","state":{"graph":{"parent":[0,0,0,3,3,3],"current":5,"highlighted":[3],"activeEdges":[[5,3]]}}},{"id":"count","state":{"graph":{"parent":[0,0,0,3,3,3]}}}]},"beats":[{"id":"merge-01","title":"Cable [0, 1] joins two roots. What happens to the group count?","summary":"Six computers, six roots. Computers 0 and 1 are each their own root.","prompt":"Cable [0, 1] is processed.","options":[{"id":"drop-to-5","label":"Computer 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 cable is the first thing that joins them. It does drop the count.","isCorrect":false},{"id":"new-root","label":"A brand-new computer becomes the parent of both","rationale":"No new computer appears. One of the two existing roots becomes the parent of the other.","isCorrect":false}],"answer":"Computer 1 points to 0, merging two roots into one. The count drops from 6 to 5."},{"id":"merge-02","title":"Cable [0, 2] arrives. Computer 2 is its own root. What links?","summary":"Root 0 holds {0, 1}; computer 2 is still its own root.","prompt":"Cable [0, 2] is processed.","options":[{"id":"drop-to-4","label":"Computer 2 points to root 0, and the count drops to 4","rationale":"Computer 0 climbs to root 0, and 2's root is 2. The roots differ, so linking 2 under 0 pulls it into {0, 1}, leaving {0, 1, 2}. The count falls to 4.","isCorrect":true},{"id":"hold","label":"The count holds, since 0 is already a root","rationale":"Computer 2 was a separate root, so this cable merges two different groups and the count does drop.","isCorrect":false},{"id":"split","label":"Computer 1 is pushed out of the group","rationale":"Merging never removes a computer from its group. Linking 2 under root 0 only adds 2 to {0, 1}.","isCorrect":false}],"answer":"Computer 2 points to root 0. Computers {0, 1, 2} now share root 0, and the count drops from 5 to 4."},{"id":"merge-34","title":"Cable [3, 4] arrives, with no link to the first group. What forms?","summary":"Computers 3 and 4 are each their own root, and computer 5 has no cable yet.","prompt":"Cable [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 computer 5, three groups remain.","isCorrect":true},{"id":"join-first","label":"Computers 3 and 4 join the group with 0, 1, 2","rationale":"No cable 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 cable merges only 3 and 4. Computer 5 still has no cable, so it remains its own group and the count lands at 3, not 2.","isCorrect":false}],"answer":"Computers 3 and 4 merge into a second group, and the count drops to 3: {0,1,2}, {3,4}, and the lone computer 5."},{"id":"redundant-21","title":"Cable [2, 1] arrives. Both already climb to root 0. What is the count now?","summary":"Computers 2 and 1 already share root 0.","prompt":"Cable [2, 1] is processed.","options":[{"id":"holds-at-3","label":"The count holds at 3, and this cable is a spare","rationale":"Both endpoints climb to the same root 0, so there is nothing to merge. This redundant cable inside one group is exactly the spare wire a later move can reuse.","isCorrect":true},{"id":"drop-to-2","label":"It drops to 2","rationale":"Dropping here would be the trap: the endpoints are already one group, so no merge happens. Only a cable joining two different roots may drop the count.","isCorrect":false},{"id":"splits","label":"The group splits back apart","rationale":"Cables only ever merge groups. A cable inside a group does nothing at all to the structure, it never splits one.","isCorrect":false}],"answer":"The count holds at 3. Both endpoints already climb to root 0, so this cable merges nothing and is left as a spare."},{"id":"merge-45","title":"Cable [4, 5] arrives. Computer 4 sits under root 3. What links?","summary":"Root 3 holds {3, 4}; computer 5 is still its own root.","prompt":"Cable [4, 5] is processed.","options":[{"id":"drop-to-2","label":"Computer 5 points to root 3, and the count drops to 2","rationale":"Computer 4 climbs to root 3, and 5's root is 5. The roots differ, so linking 5 under 3 forms {3, 4, 5}. Two groups remain: {0,1,2} and {3,4,5}.","isCorrect":true},{"id":"hold","label":"The count holds, since 4 is already placed","rationale":"Computer 5 was a separate root, so this cable merges two different groups and the count does drop.","isCorrect":false},{"id":"five-to-four","label":"Computer 5 points to 4, leaving root 3 behind","rationale":"Link root 5 under root 3. Computer 4's immediate parent sits below representative 3, so linking to 4 would miss the root.","isCorrect":false}],"answer":"Computer 5 points to root 3, forming {3, 4, 5}. The count drops from 3 to 2."},{"id":"count","title":"Every cable is processed. How many moves connect the network?","prompt":"Two groups remain, {0,1,2} and {3,4,5}, and a spare cable is sitting inside one of them.","options":[{"id":"one","label":"1, one spare bridges the single gap","rationale":"Two groups leave one gap to close, so g-1 is 1. The redundant [2,1] cable is the spare you move to bridge it.","isCorrect":true},{"id":"two","label":"2, one per group","rationale":"Two groups have only one gap between them. The answer is groups minus one, which is 1, not 2.","isCorrect":false},{"id":"zero","label":"0, the network is already connected","rationale":"Two separate groups are not connected yet. One move is still needed to bridge them.","isCorrect":false}],"answer":"1. Two groups leave one gap, and the spare [2,1] cable moves to bridge it, so groups minus one is 1 move."}]},{"id":"skip-feasibility-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you decide a cable is redundant by comparing immediate parents?","summary":"The redundancy check has to compare roots rather than parent pointers one step up. Watch n = 4 with cables [[2,3],[1,2],[3,1]], where the last cable's endpoints share a root but sit under different immediate parents.","workspacePanel":"trace","pitfall":"The union below decides two computers are already together by comparing parent[a] to parent[b], the pointers one step up, instead of climbing both to their roots.","whyItMatters":"Inside one group, computers can hang off different immediate parents while still climbing to the same root. Comparing parents one step up then reads them as separate groups, so a redundant cable is counted as a real merge and groups is dropped one too far. The fix is to compare find(a) to find(b): only a difference in roots means a genuine merge.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def makeConnected(n: int, connections: list[list[int]]) -> int:\n    parent: list[int] = list(range(n))\n    groups = n\n    def find(x: int) -> int:\n        if parent[x] != x:\n            parent[x] = find(parent[x])\n        return parent[x]\n    def union(a: int, b: int) -> bool:\n        if parent[a] == parent[b]:\n            return False\n        parent[find(a)] = find(b)\n        return True\n    for a, b in connections:\n        if union(a, b):\n            groups = groups - 1\n    return groups - 1","steps":[{"id":"merge-23","title":"Cable [2, 3] merges two roots","codeLine":11,"summary":"Four computers, groups starts at 4. Roots 2 and 3 differ, so they merge: 3 points to 2 and groups drops to 3.","state":{"graph":{"parent":[0,1,2,2],"current":3,"highlighted":[2],"activeEdges":[[3,2]]}}},{"id":"merge-12","title":"Cable [1, 2] links root 2 under root 1","codeLine":11,"summary":"Root of 1 is 1, root of 2 is 2, so they differ and merge. Root 2 points to root 1, and now computer 3 hangs under 2, whose parent is 1. Groups drops to 2.","state":{"graph":{"parent":[0,1,1,2],"current":2,"highlighted":[1],"activeEdges":[[2,1]]}}},{"id":"false-merge","title":"Cable [3, 1] is redundant, but parent[3] != parent[1]","codeLine":9,"summary":"Computers 3 and 1 both climb to root 1, so this cable merges nothing. But parent[3] is 2 and parent[1] is 1, so the immediate-parent check sees them as different and wrongly drops groups to 1.","state":{"graph":{"parent":[0,1,1,2],"current":3,"highlighted":[1],"activeEdges":[[3,1]]}}},{"id":"return","title":"It returns 0, but the truth is 1","codeLine":16,"summary":"The real groups are {0} and {1,2,3}, so two remain and the answer is 1. The false merge counted the redundant cable, leaving groups at 1 and returning 0. Computer 0 is never bridged in.","state":{"graph":{"parent":[0,1,1,2]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const parent = Array.from({ length: n }, (_, index) => index);\nlet groups = n;\nfunction find(x) {\n    if (parent[x] !== x) {\n        parent[x] = find(parent[x]);\n    }\n    return parent[x];\n}\nfunction union(a, b) {\n    if (parent[a] === parent[b]) {\n        return false;\n    }\n    parent[find(a)] = find(b);\n    return true;\n}\nfor (const [a, b] of connections) {\n    if (union(a, b)) {\n        groups = groups - 1;\n    }\n}\nreturn (groups - 1);","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"9":10,"10":11,"11":13,"12":14,"13":16,"14":17,"15":18,"16":21},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"7":{"startLine":7,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":15},"15":{"startLine":18,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const parent = Array.from({ length: n }, (_, index) => index);\nlet groups = n;\nfunction find(x: number): number {\n    if (parent[x] !== x) {\n        parent[x] = find(parent[x]);\n    }\n    return parent[x];\n}\nfunction union(a: number, b: number): boolean {\n    if (parent[a] === parent[b]) {\n        return false;\n    }\n    parent[find(a)] = find(b);\n    return true;\n}\nfor (const [a, b] of connections) {\n    if (union(a, b)) {\n        groups = groups - 1;\n    }\n}\nreturn (groups - 1);","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"9":10,"10":11,"11":13,"12":14,"13":16,"14":17,"15":18,"16":21},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"7":{"startLine":7,"endLine":9},"10":{"startLine":11,"endLine":12},"12":{"startLine":14,"endLine":15},"15":{"startLine":18,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int find(int x, List<Integer> parent) {\n    if (parent.get(x) != x) {\n        parent.set(x, find(parent.get(x), parent));\n    }\n    return parent.get(x);\n}\n\nprivate static boolean union(int a, int b, List<Integer> parent) {\n    if (parent.get(a) == parent.get(b)) {\n        return false;\n    }\n    parent.set(find(a, parent), find(b, parent));\n    return true;\n}\n\nList<Integer> parent = new ArrayList<>();\nfor (int i = 0; i < n; i++) {\n    parent.add(i);\n}\nint groups = n;\nfor (List<Integer> connection : connections) {\n    int a = connection.get(0);\n    int b = connection.get(1);\n    if (union(a, b, parent)) {\n        groups = groups - 1;\n    }\n}\nreturn (groups - 1);","lineMap":{"2":16,"3":20,"5":2,"6":3,"7":5,"9":9,"10":10,"11":12,"12":13,"13":21,"14":24,"15":25,"16":28},"statementBundles":{"2":{"startLine":16,"endLine":19},"6":{"startLine":3,"endLine":4},"7":{"startLine":5,"endLine":8},"10":{"startLine":10,"endLine":11},"12":{"startLine":13,"endLine":14},"13":{"startLine":21,"endLine":23},"15":{"startLine":25,"endLine":27}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> parent = Enumerable.Range(0, n).ToList();\nint groups = n;\nint Find(int x) {\n    if (parent[x] != x) {\n        parent[x] = Find(parent[x]);\n    }\n    return parent[x];\n    return 0;\n}\nbool Union(int a, int b) {\n    if (parent[a] == parent[b]) {\n        return false;\n    }\n    parent[Find(a)] = Find(b);\n    return true;\n    return false;\n}\nforeach (var item in connections) {\n    int a = item[0];\n    int b = item[1];\n    if (Union(a, b)) {\n        groups = groups - 1;\n    }\n}\nreturn groups - 1;","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"9":11,"10":12,"11":14,"12":15,"13":18,"14":21,"15":22,"16":25},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"7":{"startLine":7,"endLine":10},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":17},"13":{"startLine":18,"endLine":20},"15":{"startLine":22,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int)> find;\n\nvector<int> parent;\nfor (int value = 0; value < n; value++) {\n    parent.push_back(value);\n}\nint groups = n;\nfind = [&]( int x ) -> int {\n    if (parent[x] != x) {\n        parent[x] = find(parent[x]);\n    }\n    return parent[x];\n};\nauto union_ = [&]( int a, int b ) -> bool {\n    if (parent[a] == parent[b]) {\n        return false;\n    }\n    parent[find(a)] = find(b);\n    return true;\n};\nfor (vector<int> item : connections) {\n    int a = item[0];\n    int b = item[1];\n    if (union_(a, b)) {\n        groups = groups - 1;\n    }\n}\nreturn (groups - 1);","lineMap":{"2":3,"3":7,"5":9,"6":10,"7":12,"9":15,"10":16,"11":18,"12":19,"13":21,"14":24,"15":25,"16":28},"statementBundles":{"2":{"startLine":3,"endLine":6},"3":{"startLine":7,"endLine":8},"6":{"startLine":10,"endLine":11},"7":{"startLine":12,"endLine":14},"10":{"startLine":16,"endLine":17},"12":{"startLine":19,"endLine":20},"13":{"startLine":21,"endLine":23},"15":{"startLine":25,"endLine":27}},"alternateStyles":{"close-to-source":{"code":"function<int(int)> find;\n\nvector<int> parent = ([&] { vector<int> values; for (int value = 0; value < n; value++) values.push_back(value); return values; }());\nint groups = n;\nfind = [&]( int x ) -> int {\n    if (parent[x] != x) {\n        parent[x] = find(parent[x]);\n    }\n    return parent[x];\n};\nauto union_ = [&]( int a, int b ) -> bool {\n    if (parent[a] == parent[b]) {\n        return false;\n    }\n    parent[find(a)] = find(b);\n    return true;\n};\nfor (vector<int> item : connections) {\n    int a = item[0];\n    int b = item[1];\n    if (union_(a, b)) {\n        groups = groups - 1;\n    }\n}\nreturn (groups - 1);","lineMap":{"2":3,"3":4,"5":6,"6":7,"7":9,"9":12,"10":13,"11":15,"12":16,"13":18,"14":21,"15":22,"16":25},"statementBundles":{"3":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":8},"7":{"startLine":9,"endLine":11},"10":{"startLine":13,"endLine":14},"12":{"startLine":16,"endLine":17},"13":{"startLine":18,"endLine":20},"15":{"startLine":22,"endLine":24}}}}}}}},{"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":["Merging cables by their roots, counting the surviving groups, and subtracting one named the moves in the sample, with the feasibility check guarding the impossible case.","Before coding it, push on the inputs that stress how the count is seeded and where the n-1 cable bar bites."]},{"id":"already-connected-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"The cables already wire every computer into one group. How many moves?","summary":"n = 5 with cables forming a chain 0-1-2-3-4, so every computer reaches every other.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,0,0,0]}}}]},"options":[{"id":"zero","label":"0, nothing needs moving","rationale":"One group means no gap to close, and groups minus one is zero. The chain has 4 cables for 5 computers, so the feasibility bar is met and the formula returns 0 with no special case.","isCorrect":true},{"id":"one","label":"1, there is always one move","rationale":"When the network is already one group there is no gap left to bridge, so the answer is exactly groups minus one, which is 0.","isCorrect":false},{"id":"minus-one","label":"-1, a chain is not really connected","rationale":"A chain through all computers means each reaches every other, so it is one group. -1 is only for too few cables, and 4 cables clear the bar for 5 computers.","isCorrect":false}],"answer":"0. The chain is already one group, so there is no gap, and groups minus one is 0."},{"id":"isolated-computer-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"A computer sits in no cable while the others merge. Does it count?","summary":"n = 4 with cables [[0,1],[1,2],[0,2]], so computers 0, 1, 2 wire into one group and computer 3 never appears in any cable.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,0,0,3]}}}]},"options":[{"id":"one-move","label":"1, the lone computer is its own group and needs a bridge","rationale":"Computers 0, 1, 2 merge into one group and computer 3 still points at itself, so two groups remain. Seeding parent for all n computers is what keeps 3 counted, and groups minus one is 1. The three cables for four computers clear the n-1 bar, with [0,2] left as the spare that bridges computer 3.","isCorrect":true},{"id":"zero","label":"0, only computers in a cable count","rationale":"A computer absent from every cable is still a group of one. It must be bridged in, so it adds to the move count, not removed from it.","isCorrect":false},{"id":"minus-one","label":"-1, computer 3 can never be reached","rationale":"That would only hold if the cables fell below the n-1 bar of 3. Here three cables clear it, and the spare [0,2] reaches computer 3 in one move, so the answer is 1, not -1.","isCorrect":false}],"answer":"It counts. Computers {0,1,2} merge into one group and computer 3 stays its own, so two groups remain and one move bridges the lone computer."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Guard the impossible case first, then merge by roots and read the moves off the surviving group count.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest","state":{"graph":{"parent":[0,1,2,3,4,5]}}}]},"body":["Reject the impossible case up front: with fewer than n-1 cables, return -1. Otherwise start each computer as its own parent, with a find that climbs to a root and flattens what it passes. For every cable, climb both endpoints to their roots and link one root under the other, breaking ties by rank.","At the end, count the computers still pointing at themselves, and return that group count minus one."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the network solver","eyebrow":"Code the rule","summary":"Guard feasibility, then merge roots and return groups - 1.","workspacePanel":"code","checkpoints":[{"id":"init-arrays","title":"Initialize parent and rank","description":"Create union-find parent and rank arrays for all computers.","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":["Only initializing parent for computers that appear in a cable","Forgetting the rank array"],"hint":"Every computer starts as its own component.","semanticSpec":{"intent":"Initialize disjoint-set state for all computers.","doneWhen":"Parent and rank arrays are initialized across the node range.","shouldFailWhen":"Some computers have no parent entry or rank state is missing.","roles":["parent array","rank array","computer labels"],"mustProve":["Each node starts as its own parent.","Rank or size state is initialized for union balancing."],"mustNotAccept":["Only tracking nodes that appear in edges."]}},{"id":"find-function","title":"Compress paths in find","description":"Implement `find` so it follows parents to the root and compresses the path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"implements_path_compression","scope":"find-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Returning only the immediate parent","Not writing the compressed root back"],"hint":"If a node is not its own parent, recursively find the root and store it.","semanticSpec":{"intent":"Resolve the representative root while shortening future paths.","doneWhen":"The find helper recursively follows parents and writes the representative back.","shouldFailWhen":"Find does not compress or returns an unresolved parent.","roles":["find helper","parent array","representative root"],"mustProve":["Find walks parent links until a root is reached.","Find stores the representative root for compression."],"mustNotAccept":["A find function with no parent-link recursion or loop."]}},{"id":"union-function","title":"Union by representatives","description":"Merge two computers by first finding their component roots.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"unions_by_root","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Linking raw nodes instead of roots","Merging even when the roots are already equal"],"hint":"Call find on both endpoints before writing any parent link.","semanticSpec":{"intent":"Merge components by representative roots.","doneWhen":"Union finds both roots and links one root to the other if they differ.","shouldFailWhen":"Union links non-root nodes directly.","roles":["union helper","root representatives","parent links"],"mustProve":["Union uses find results for both endpoints.","Union writes a parent link between roots."],"mustNotAccept":["Directly setting `parent[x] = y` without root lookup."]}},{"id":"union-by-rank","title":"Use rank when linking roots","description":"Attach the shallower root under the deeper root and update rank on ties.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"applies_ranked_union","scope":"union-function","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Ignoring rank completely","Forgetting to increment rank on a tie"],"hint":"Compare root ranks before choosing which parent pointer to update.","semanticSpec":{"intent":"Keep union-find trees shallow with a rank heuristic.","doneWhen":"Union compares ranks and increments rank when equal-ranked roots merge.","shouldFailWhen":"Union always links the second root under the first without rank logic.","roles":["rank array","root representatives","parent link"],"mustProve":["Rank controls which root becomes parent.","Rank is updated when equal ranks are merged."],"mustNotAccept":["No rank or size heuristic."]}},{"id":"process-connections","title":"Union every cable","description":"Scan the connection list and union both endpoints of each cable.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"scans_merge_pair_sequence","scope":"process-edges","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Skipping duplicate-looking but valid edges","Only processing one endpoint"],"hint":"Each connection is a pair of computers to merge.","semanticSpec":{"intent":"Apply union-find merging to every given cable.","doneWhen":"The solution loops through the edge list and calls union on each pair.","shouldFailWhen":"Connections are not scanned or union is not called for them.","roles":["connection pair","union helper"],"mustProve":["The edge list is scanned.","Each pair can trigger a union operation."],"mustNotAccept":["Counting edges without merging components."]}},{"id":"count-components","title":"Count connected components","description":"After all unions, count how many distinct representative roots remain.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"union-find","fact":"counts_distinct_roots","scope":"count-provinces","readMode":"union-find-value-query-v1"}]},"commonMistakes":["Counting parent values without compressing roots","Counting cables instead of components"],"hint":"A computer starts a component only if it is its own representative after find.","semanticSpec":{"intent":"Count the remaining disjoint-set representatives.","doneWhen":"The solution calls find over the node range and counts representative roots.","shouldFailWhen":"It counts raw parents or edge groups without resolving roots.","roles":["component count","find helper","representative roots"],"mustProve":["The final count is based on distinct roots."],"mustNotAccept":["Returning the number of edges or redundant cables."]}},{"id":"return-operations","title":"Return required operations","description":"Return the numeric number of cable moves needed after component counting.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"commonMistakes":["Returning the component count directly","Returning a boolean connectivity result"],"hint":"Connecting `components` groups needs `components - 1` operations.","semanticSpec":{"intent":"Return the final numeric operation count.","doneWhen":"The terminal return is a numeric answer derived from the connected component count.","shouldFailWhen":"The function returns the parent array, a boolean, or the raw edge count.","roles":["component count","operation count","terminal return"],"mustProve":["The function returns a numeric answer after component counting."],"mustNotAccept":["Returning non-answer state."]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Below n-1 cables it is impossible; otherwise merge every cable, and the answer is the surviving group count minus one.","workspacePanel":"code","body":["Computers in one group are exactly those that union together, so merging each cable collapses every group down to a single root. A cable inside an existing group merges nothing and is left as spare wire.","Each gap between two groups takes one spare cable to bridge, so g groups need g-1 moves, and the only impossible case is too few cables to span the network at all."],"takeaways":[{"title":"Moves are gaps, and gaps are groups minus one","body":"Linking g groups closes g-1 gaps, and each redundant cable inside a group is the spare that bridges one, so the answer is the surviving root count minus one."},{"title":"Too few cables is the only -1","body":"Spanning n computers needs at least n-1 cables, and a move relocates a cable rather than adding one, so the cable-count precheck is what separates impossible from solvable."},{"title":"Near-linear, because the trees stay flat","body":"Path compression and union by rank keep each find and union nearly constant, so n computers and e cables 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"},"complexity":{"time":"O((n+e)*alpha(n))","space":"O(n)","explanation":"Union-find initializes n computers, scans e connections, and performs almost-constant amortized find and union operations."}}
