Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Graph Algorithms
MediumLC 1135

Connecting Cities With Minimum Cost (LeetCode 1135)

Target Frequency:AmazonGoogleUber

There are n cities, labeled 1 to n. Each connections[i] = [xi, yi, cost_i] says you can build a two-way link between city xi and city yi for cost_i.

Choose links so that every city can reach every other city through built links, and pay as little as possible in total. Return that smallest total, or -1 if even building every link leaves some cities cut off.

Worked Examples

Example 1
Input:n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output:6
561123
Explanation: Any two links connect three cities, so take the two cheapest: 2-3 for 1 and 1-2 for 5.
Example 2
Input:n = 4, connections = [[1,2,3],[3,4,4]]
Output:-1
341234
Explanation: No link joins the pair {1, 2} to the pair {3, 4}, so the cities can't all be connected.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 104

  • 1 <= connections.length <= 104

  • connections[i].length == 3

  • 1 <= xi, yi <= n

  • xi != yi

  • 0 <= cost_i <= 105

Deep-Dive & Conceptual Insights

Core Insight

Take links from cheapest to most expensive and keep each one that joins two cities not yet connected (a Union-Find find tells); n - 1 kept links is a cheapest spanning tree, fewer means some city can't be reached.

Real-World Scenario & Production Applications

Laying cable, fibre or pipes between sites at the smallest total cost is a minimum spanning tree problem; so is clustering by stopping Kruskal early (single-linkage clustering). The same sort-and-union loop runs over any weighted edge list.

Step-by-Step Execution Trace Table

Input n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]], sorted by cost: [2,3,1], [1,2,5], [1,3,6].

StepEdge [u, v, w]find(u), find(v)Same group?Actionmst_costedges_count
1[2, 3, 1]2, 3Notake it, parent[2] = 311
2[1, 2, 5]1, 3Notake it, parent[1] = 362 = n - 1, stop
Endedges_count == n - 1, return mst_cost6

Input n = 4, connections = [[1,2,3],[3,4,4]]: both edges are taken (edges_count = 2), the list ends with 2 < n - 1 = 3, so the answer is -1.

Trace Inputn = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Expected6

Input n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]], sorted by cost: [2,3,1], [1,2,5], [1,3,6].

StepEdge [u, v, w]find(u), find(v)Same group?Actionmst_costedges_count
1[2, 3, 1]2, 3Notake it, parent[2] = 311
2[1, 2, 5]1, 3Notake it, parent[1] = 362 = n - 1, stop
Endedges_count == n - 1, return mst_cost6

Input n = 4, connections = [[1,2,3],[3,4,4]]: both edges are taken (edges_count = 2), the list ends with 2 < n - 1 = 3, so the answer is -1.

Code Shape
Archetype Code Shape
Python
1The cheapest link between two separate groups is always safe to build; a link inside one group only closes a cycle.
2`find(u) != find(v)` says the ends are in different groups: take the edge, join the roots (`parent[root_u] = root_v`), add `w` to `mst_cost`, and count it in `edges_count`.
3`parent = list(range(n + 1))`, a `find` with path halving, sort `connections` by cost, loop and take safe edges, stop at `n - 1` edges.
4The trap: return `mst_cost` only if `edges_count == n - 1`; fewer edges means the cities are not all connected, so return `-1`.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

To join every city at the lowest total cost you need a minimum spanning tree: n - 1 links, no cycles, smallest total weight. Kruskal's algorithm builds it greedily: look at the links from cheapest to most expensive, and take a link only when its two cities are still in different groups. A Union-Find (parent plus find) answers "same group?" almost instantly, and joining two groups is one assignment.

🏟️ The Analogy: Building Bridges Between Islands

Picture every city as its own island. You have a price list of possible bridges. Go down the list from the cheapest: if a bridge links two islands that are not yet reachable from each other, build it and treat the two as one bigger island. If they are already reachable, the bridge would only make a loop, so skip it. When everything is one island you are done; if the list runs out first, some islands can never be reached.

🔑 Why It Works

Why the cheapest crossing edge is safe: any full wiring must cross the gap between two separate groups somewhere; if it used a more expensive crossing, swapping in the cheaper one keeps everything connected and never costs more. An edge whose ends share a root would only close a cycle, so skipping it loses nothing.

  • Returning the partial cost when the graph is disconnected: after the loop, edges_count < n - 1 means some cities were never reached. Return -1, not mst_cost: on n = 4, [[1,2,3],[3,4,4]] the partial cost is 7 but the answer is -1.

  • Joining the nodes instead of the roots: parent[u] = v can cut u off from its own group and leave two roots for one group. Always join parent[root_u] = root_v.

  • No path compression: without the parent[x] = parent[parent[x]] step, chains grow and each find can walk O(n) links, making the whole run O(E * V).

  • Off-by-one on labels: cities are labeled 1..n, so parent needs n + 1 slots; list(range(n)) crashes on city n.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Connect all the cities" with the "minimum total cost" over a list of weighted links: every city must be reachable, but the cost is paid per link, not per route. That is a minimum spanning tree, and with the links given as an edge list, Kruskal's MST (sort plus Union-Find) is the direct fit.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

The edges taken so far form a forest that is part of some minimum spanning tree, and find gives one root to exactly the cities they connect; an edge is taken exactly when find(u) != find(v).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • connections.sort(key=lambda e: e[2]): sort by the cost, the third value. A plain connections.sort() orders by the first city, so expensive links can be taken first: Example 1 returns 11 instead of 6.

  • Two links between the same pair of cities need no special case: once the cheaper one is taken, the other has find(u) == find(v) and is skipped like any link that would close a cycle.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is a minimum spanning tree, so I'd use Kruskal's MST. I sort the connections by cost and keep a Union-Find over the cities. For each connection, cheapest first, I find both cities' roots. If the roots differ, the link joins two separate groups, so I take it: I join the roots, add its cost, and count it. If the roots match, it would only close a cycle, so I skip it. Taking the cheapest link across any gap is safe, because any full wiring must cross that gap somewhere and swapping in the cheaper link never costs more. I stop once I have n minus one links. The trap is the end: if I finish the list with fewer than n minus one links, some cities are unreachable and I return minus one, not the partial cost. Sorting dominates, so it's O(E log E) time, with O(V) space for the parent array.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(E log E)

Look at the code: connections.sort(key=lambda e: e[2]) costs O(E log E). The loop visits each of the E edges at most once; each iteration calls find twice, and with path halving a find costs amortized O(log V) at worst (nearly constant in practice), which is below the sort's per-edge O(log E). Total: O(E log E).

SPACE COMPLEXITY

O(V)

parent holds n + 1 entries: O(V). The edges are sorted in place in the input list; the counters are O(1). (Python's sort may use a temporary buffer while it runs.)

Formal Recurrence Relation

T(V, E) = O(E log E) + E · O(find) = O(E log E)

Derivation Progression

Build Union-Find

O(V)

parent = list(range(n + 1)).

Sort edges

O(E log E)

connections.sort(key=lambda e: e[2]).

Scan edges

E × 2 finds

Each edge is looked at once; find with path halving is nearly constant, at most O(log V) amortized.

Total

O(E log E)

The sort dominates the scan.

Variable Definitions

VVV

Number of cities, n

EEE

Number of candidate links, len(connections)

Memory Architecture & Bounds

🟣 Call Stack

O(1): find is iterative

🔵 Auxiliary Heap

O(V): the parent array

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(Elog⁡E)O(E \log E)O(ElogE): the sort runs even if the first n - 1 edges already connect everything

Average Case

O(Elog⁡E)O(E \log E)O(ElogE)

Worst Case

O(Elog⁡E)O(E \log E)O(ElogE)

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Scale signal: trying every set of n−1n - 1n−1 links is exponential; sorting the E≤104E \le 10^4E≤104 links once and one near-constant find pair per link is about 104⋅log⁡2104≈1.3×10510^4 \cdot \log_2 10^4 \approx 1.3 \times 10^5104⋅log2​104≈1.3×105 steps.

CONSTRAINTS & BOUNDS

n≤104n \le 10^4n≤104 cities, E≤104E \le 10^4E≤104 links, costs up to 10510^5105: the total is at most 104⋅105=10910^4 \cdot 10^5 = 10^9104⋅105=109, which fits a 32-bit signed integer.

FAANG PRODUCTION TRAPS & EDGE CASES

At scale, Kruskal needs the whole edge list sorted up front; when edges arrive as a stream or don't fit in memory, sort externally or use Prim's algorithm on an adjacency structure instead.

Core Algorithmic State Invariants

  1. Example 1, Cheapest First

Sorted by cost: 2-3 (1), 1-2 (5), 1-3 (6). Link 2-3 joins two groups, then 1-2 joins city 1: that is n - 1 = 2 links, so the loop stops at 6 and never reads 1-3.

  1. A Link Inside One Group Is Skipped

n = 4, [[1,2,1],[2,3,2],[1,3,3],[3,4,4]]: after 1-2 and 2-3, find(1) == find(3), so 1-3 would close a cycle and is skipped; 3-4 completes the tree at 1 + 2 + 4 = 7.

  1. Ties Change the Tree, Not the Cost

When two links cost the same, the sort may put either first, and the chosen links can differ, but every minimum spanning tree has the same total cost, so the answer does not change.

Theory Context•Graph Algorithms
MediumLC 1135

Connecting Cities With Minimum Cost (LeetCode 1135)

Target Frequency:AmazonGoogleUber

There are n cities, labeled 1 to n. Each connections[i] = [xi, yi, cost_i] says you can build a two-way link between city xi and city yi for cost_i.

Choose links so that every city can reach every other city through built links, and pay as little as possible in total. Return that smallest total, or -1 if even building every link leaves some cities cut off.

Worked Examples

Example 1
Input:n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output:6
561123
Explanation: Any two links connect three cities, so take the two cheapest: 2-3 for 1 and 1-2 for 5.
Example 2
Input:n = 4, connections = [[1,2,3],[3,4,4]]
Output:-1
341234
Explanation: No link joins the pair {1, 2} to the pair {3, 4}, so the cities can't all be connected.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 104

  • 1 <= connections.length <= 104

  • connections[i].length == 3

  • 1 <= xi, yi <= n

  • xi != yi

  • 0 <= cost_i <= 105

Deep-Dive & Conceptual Insights

Core Insight

Take links from cheapest to most expensive and keep each one that joins two cities not yet connected (a Union-Find find tells); n - 1 kept links is a cheapest spanning tree, fewer means some city can't be reached.

Real-World Scenario & Production Applications

Laying cable, fibre or pipes between sites at the smallest total cost is a minimum spanning tree problem; so is clustering by stopping Kruskal early (single-linkage clustering). The same sort-and-union loop runs over any weighted edge list.

Step-by-Step Execution Trace Table

Input n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]], sorted by cost: [2,3,1], [1,2,5], [1,3,6].

StepEdge [u, v, w]find(u), find(v)Same group?Actionmst_costedges_count
1[2, 3, 1]2, 3Notake it, parent[2] = 311
2[1, 2, 5]1, 3Notake it, parent[1] = 362 = n - 1, stop
Endedges_count == n - 1, return mst_cost6

Input n = 4, connections = [[1,2,3],[3,4,4]]: both edges are taken (edges_count = 2), the list ends with 2 < n - 1 = 3, so the answer is -1.

Trace Inputn = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Expected6

Input n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]], sorted by cost: [2,3,1], [1,2,5], [1,3,6].

StepEdge [u, v, w]find(u), find(v)Same group?Actionmst_costedges_count
1[2, 3, 1]2, 3Notake it, parent[2] = 311
2[1, 2, 5]1, 3Notake it, parent[1] = 362 = n - 1, stop
Endedges_count == n - 1, return mst_cost6

Input n = 4, connections = [[1,2,3],[3,4,4]]: both edges are taken (edges_count = 2), the list ends with 2 < n - 1 = 3, so the answer is -1.

Code Shape
Archetype Code Shape
Python
1The cheapest link between two separate groups is always safe to build; a link inside one group only closes a cycle.
2`find(u) != find(v)` says the ends are in different groups: take the edge, join the roots (`parent[root_u] = root_v`), add `w` to `mst_cost`, and count it in `edges_count`.
3`parent = list(range(n + 1))`, a `find` with path halving, sort `connections` by cost, loop and take safe edges, stop at `n - 1` edges.
4The trap: return `mst_cost` only if `edges_count == n - 1`; fewer edges means the cities are not all connected, so return `-1`.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

To join every city at the lowest total cost you need a minimum spanning tree: n - 1 links, no cycles, smallest total weight. Kruskal's algorithm builds it greedily: look at the links from cheapest to most expensive, and take a link only when its two cities are still in different groups. A Union-Find (parent plus find) answers "same group?" almost instantly, and joining two groups is one assignment.

🏟️ The Analogy: Building Bridges Between Islands

Picture every city as its own island. You have a price list of possible bridges. Go down the list from the cheapest: if a bridge links two islands that are not yet reachable from each other, build it and treat the two as one bigger island. If they are already reachable, the bridge would only make a loop, so skip it. When everything is one island you are done; if the list runs out first, some islands can never be reached.

🔑 Why It Works

Why the cheapest crossing edge is safe: any full wiring must cross the gap between two separate groups somewhere; if it used a more expensive crossing, swapping in the cheaper one keeps everything connected and never costs more. An edge whose ends share a root would only close a cycle, so skipping it loses nothing.

  • Returning the partial cost when the graph is disconnected: after the loop, edges_count < n - 1 means some cities were never reached. Return -1, not mst_cost: on n = 4, [[1,2,3],[3,4,4]] the partial cost is 7 but the answer is -1.

  • Joining the nodes instead of the roots: parent[u] = v can cut u off from its own group and leave two roots for one group. Always join parent[root_u] = root_v.

  • No path compression: without the parent[x] = parent[parent[x]] step, chains grow and each find can walk O(n) links, making the whole run O(E * V).

  • Off-by-one on labels: cities are labeled 1..n, so parent needs n + 1 slots; list(range(n)) crashes on city n.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Connect all the cities" with the "minimum total cost" over a list of weighted links: every city must be reachable, but the cost is paid per link, not per route. That is a minimum spanning tree, and with the links given as an edge list, Kruskal's MST (sort plus Union-Find) is the direct fit.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

The edges taken so far form a forest that is part of some minimum spanning tree, and find gives one root to exactly the cities they connect; an edge is taken exactly when find(u) != find(v).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • connections.sort(key=lambda e: e[2]): sort by the cost, the third value. A plain connections.sort() orders by the first city, so expensive links can be taken first: Example 1 returns 11 instead of 6.

  • Two links between the same pair of cities need no special case: once the cheaper one is taken, the other has find(u) == find(v) and is skipped like any link that would close a cycle.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is a minimum spanning tree, so I'd use Kruskal's MST. I sort the connections by cost and keep a Union-Find over the cities. For each connection, cheapest first, I find both cities' roots. If the roots differ, the link joins two separate groups, so I take it: I join the roots, add its cost, and count it. If the roots match, it would only close a cycle, so I skip it. Taking the cheapest link across any gap is safe, because any full wiring must cross that gap somewhere and swapping in the cheaper link never costs more. I stop once I have n minus one links. The trap is the end: if I finish the list with fewer than n minus one links, some cities are unreachable and I return minus one, not the partial cost. Sorting dominates, so it's O(E log E) time, with O(V) space for the parent array.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(E log E)

Look at the code: connections.sort(key=lambda e: e[2]) costs O(E log E). The loop visits each of the E edges at most once; each iteration calls find twice, and with path halving a find costs amortized O(log V) at worst (nearly constant in practice), which is below the sort's per-edge O(log E). Total: O(E log E).

SPACE COMPLEXITY

O(V)

parent holds n + 1 entries: O(V). The edges are sorted in place in the input list; the counters are O(1). (Python's sort may use a temporary buffer while it runs.)

Formal Recurrence Relation

T(V, E) = O(E log E) + E · O(find) = O(E log E)

Derivation Progression

Build Union-Find

O(V)

parent = list(range(n + 1)).

Sort edges

O(E log E)

connections.sort(key=lambda e: e[2]).

Scan edges

E × 2 finds

Each edge is looked at once; find with path halving is nearly constant, at most O(log V) amortized.

Total

O(E log E)

The sort dominates the scan.

Variable Definitions

VVV

Number of cities, n

EEE

Number of candidate links, len(connections)

Memory Architecture & Bounds

🟣 Call Stack

O(1): find is iterative

🔵 Auxiliary Heap

O(V): the parent array

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(Elog⁡E)O(E \log E)O(ElogE): the sort runs even if the first n - 1 edges already connect everything

Average Case

O(Elog⁡E)O(E \log E)O(ElogE)

Worst Case

O(Elog⁡E)O(E \log E)O(ElogE)

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Scale signal: trying every set of n−1n - 1n−1 links is exponential; sorting the E≤104E \le 10^4E≤104 links once and one near-constant find pair per link is about 104⋅log⁡2104≈1.3×10510^4 \cdot \log_2 10^4 \approx 1.3 \times 10^5104⋅log2​104≈1.3×105 steps.

CONSTRAINTS & BOUNDS

n≤104n \le 10^4n≤104 cities, E≤104E \le 10^4E≤104 links, costs up to 10510^5105: the total is at most 104⋅105=10910^4 \cdot 10^5 = 10^9104⋅105=109, which fits a 32-bit signed integer.

FAANG PRODUCTION TRAPS & EDGE CASES

At scale, Kruskal needs the whole edge list sorted up front; when edges arrive as a stream or don't fit in memory, sort externally or use Prim's algorithm on an adjacency structure instead.

Core Algorithmic State Invariants

  1. Example 1, Cheapest First

Sorted by cost: 2-3 (1), 1-2 (5), 1-3 (6). Link 2-3 joins two groups, then 1-2 joins city 1: that is n - 1 = 2 links, so the loop stops at 6 and never reads 1-3.

  1. A Link Inside One Group Is Skipped

n = 4, [[1,2,1],[2,3,2],[1,3,3],[3,4,4]]: after 1-2 and 2-3, find(1) == find(3), so 1-3 would close a cycle and is skipped; 3-4 completes the tree at 1 + 2 + 4 = 7.

  1. Ties Change the Tree, Not the Cost

When two links cost the same, the sort may put either first, and the chosen links can differ, but every minimum spanning tree has the same total cost, so the answer does not change.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•