Connecting Cities With Minimum Cost Problem
Description
LeetCode Problem 1135.
There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [x_i, y_i, cost_i] indicates that the cost of connecting city x_i and city y_i (bidirectional connection) is cost_i.
Return the minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1,
The cost is the sum of the connections' costs used.
Example 1:

Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2.
Example 2:

Input: n = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
Explanation: There is no way to connect all cities even if all edges are used.
Constraints:
1 <= n <= 10^41 <= connections.length <= 10^4connections[i].length == 31 <= x_i, y_i <= nx_i != y_i0 <= cost_i <= 10^5
Solution
Approach: Kruskal's Algorithm with Union-Find
A cheapest set of connections that links all cities never contains a cycle: on a cycle, dropping any one edge keeps everything connected and does not raise the cost. So the answer is the total weight of a minimum spanning tree, and Kruskal's algorithm builds one greedily:
- Sort the connections by cost.
- Go through them from cheapest to most expensive. If the two cities are already in the same component, the edge would only close a cycle, so skip it. Otherwise take it: merge the two components and add its cost.
- Each edge taken joins two components, so after
n - 1edges only one component is left and we can stop.
A union-find structure keeps track of the components; find returns the representative of a city's component, and path halving keeps the trees shallow.
If we run out of connections while more than one component remains, some city cannot be reached at all, and the answer is -1 (Example 2). Note that duplicate connections between the same two cities are possible; the cheaper one is seen first, and the others are skipped as cycles.
Complexity: O(m log m) time for sorting the m connections (the union-find work is almost linear), and O(n) extra space for the union-find array.
class Solution:
def minimumCost(self, n: int, connections: List[List[int]]) -> int:
parent = list(range(n + 1))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
components = n
total = 0
for x, y, cost in sorted(connections, key=lambda e: e[2]):
rx, ry = find(x), find(y)
if rx == ry:
continue # already connected: this edge would form a cycle
parent[rx] = ry
total += cost
components -= 1
if components == 1:
return total
return total if components == 1 else -1