Connecting Cities With Minimum Cost, solved and explained
Connecting Cities With Minimum Cost asks for the total weight of a minimum spanning tree, or -1 when the roads cannot join every city. Sort the roads by cost and add each one that links two separate groups, tracked with union-find; if you finish with more than one group, the answer is -1. That is Kruskal's algorithm, O(m log m) for m roads.
By Evin JohnPublished 8 min read
The problem, restated
There are n cities labeled 1 to n. You get a list of road proposals; each one names two cities and the price to build a road between them, and a built road can be driven both ways. Choose which roads to build so that you can travel from any city to any other, and spend as little as possible in total. If even building every proposal leaves some city unreachable, return -1.
| n | Road proposals (a, b, cost) | Result | Reason |
|---|---|---|---|
| 4 | (1,2,3) (2,3,1) (3,4,4) (1,4,2) (1,3,5) | 6 | Build 2-3, 1-4 and 1-2 |
| 3 | (1,2,5) | -1 | City 3 has no road at all |
| 2 | (1,2,8) (1,2,3) | 3 | Two offers for the same pair; take the cheaper |
| 1 | none | 0 | A single city is already connected |
Clarify early: are costs positive, can the same pair appear twice, and what should a single city return? Positive costs mean the cheapest network never contains a cycle, since dropping any road on a cycle keeps everything connected and saves money. A network with no cycle that reaches all n cities is a spanning tree, and it always has exactly n − 1 roads.
Slow approach: test every candidate tree
Since the answer has exactly n − 1 roads, a brute force can try every group of n − 1 proposals, keep the groups that connect all cities, and return the cheapest. With m proposals that is "m choose n − 1" groups, each checked in about O(n) time. For 20 roads and 8 cities that is already tens of thousands of groups, so it only serves to state the problem precisely and to check a faster answer on tiny inputs.
from itertools import combinations
def min_network_cost_slow(n, links):
if n == 1:
return 0
best = -1
for group in combinations(links, n - 1):
owner = list(range(n + 1))
def top(c):
while owner[c] != c:
c = owner[c]
return c
for a, b, _ in group:
owner[top(a)] = top(b)
if len({top(c) for c in range(1, n + 1)}) == 1:
price = sum(cost for _, _, cost in group)
if best == -1 or price < best:
best = price
return bestMain approach: Kruskal's greedy choice
Kruskal looks at roads from cheapest to most expensive. A road is accepted if its two cities are currently in different groups; otherwise it would close a loop and is skipped. The cut property is the reason this greedy choice is safe: for any split of the cities into two sides, the cheapest road crossing the split belongs to some minimum spanning tree, and the cheapest road between two separate groups is exactly such a crossing road.
Union-find (also called a disjoint set union) stores a parent pointer per city. find walks up to the group's root, and union hangs one root under the other. Two small optimizations keep the trees flat: path compression points every visited city straight at the root, and union by size hangs the smaller group under the larger one. Together they make each operation close to constant time.
To detect the impossible case, keep a counter of groups that starts at n and drops by one with each accepted road. When it reaches 1 you can return immediately. If the loop runs out of roads first, the map is disconnected.
def min_network_cost(n, links):
parent = list(range(n + 1))
size = [1] * (n + 1)
def find(city):
root = city
while parent[root] != root:
root = parent[root]
while parent[city] != root: # point the whole path at the root
parent[city], city = root, parent[city]
return root
total = 0
groups = n
for a, b, cost in sorted(links, key=lambda road: road[2]):
ra, rb = find(a), find(b)
if ra == rb:
continue
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
total += cost
groups -= 1
if groups == 1:
return total
return total if groups == 1 else -1function minNetworkCost(n, links) {
const parent = Array.from({ length: n + 1 }, (_, i) => i);
const size = new Array(n + 1).fill(1);
function find(city) {
let root = city;
while (parent[root] !== root) root = parent[root];
while (parent[city] !== root) {
const next = parent[city];
parent[city] = root;
city = next;
}
return root;
}
const roads = [...links].sort((p, q) => p[2] - q[2]);
let total = 0;
let groups = n;
for (const [a, b, cost] of roads) {
let ra = find(a);
let rb = find(b);
if (ra === rb) continue;
if (size[ra] < size[rb]) [ra, rb] = [rb, ra];
parent[rb] = ra;
size[ra] += size[rb];
total += cost;
groups -= 1;
if (groups === 1) return total;
}
return groups === 1 ? total : -1;
}Walk through the first example. Sorted, the roads are 2-3 (1), 1-4 (2), 1-2 (3), 3-4 (4), 1-3 (5). Taking 2-3 leaves three groups, 1-4 leaves two, and 1-2 merges the last two, so the function returns 1 + 2 + 3 = 6 without even looking at the two priciest roads.
Prim's algorithm, the other standard answer
Prim starts from one city and keeps a min-heap of roads leaving the tree it has built so far. Each step pops the cheapest road; if it leads to a city already in the tree, discard it, otherwise add that city and push its roads. If the heap empties before all n cities join, return -1.
import heapq
def min_network_cost_prim(n, links):
roads = [[] for _ in range(n + 1)]
for a, b, cost in links:
roads[a].append((cost, b))
roads[b].append((cost, a))
joined = [False] * (n + 1)
heap = [(0, 1)]
total = count = 0
while heap and count < n:
cost, city = heapq.heappop(heap)
if joined[city]:
continue
joined[city] = True
total += cost
count += 1
for option in roads[city]:
if not joined[option[1]]:
heapq.heappush(heap, option)
return total if count == n else -1Complexity
| Approach | Time | Extra space |
|---|---|---|
| Every group of n − 1 roads | O(C(m, n − 1) · n) | O(n) |
| Kruskal + union-find | O(m log m), dominated by sorting | O(n + m) with the sorted copy |
| Prim + binary heap | O(m log m) | O(n + m) for adjacency lists and heap |
Edge cases
- n = 1: zero roads are needed, so the answer is 0 even with an empty list.
- A city that appears in no proposal: the answer is -1 no matter how many other roads exist.
- Duplicate pairs with different prices: the cheaper one is taken and the other becomes a loop.
- Two clusters that are each well connected but have no road between them: -1, and Kruskal reaches the end with groups still at 2.
- Large totals in fixed-width languages. Python and JavaScript numbers are fine at interview sizes, but in Java or C++ think about whether the sum can overflow a 32-bit int.
Mistakes interviewers see often
- Returning the total without checking connectivity, so a disconnected map gets a small number instead of -1.
- Treating the graph as directed and only pushing one direction of each road in Prim.
- Building a shortest-path tree with Dijkstra. Shortest paths from one city and the cheapest network are different questions with different answers.
- Sorting in JavaScript without a comparator, which orders costs as text.
- Forgetting that labels start at 1 and sizing the arrays as n instead of n + 1.
- Claiming union-find is O(1) per call without the optimizations. Without them a long chain can make find linear.
A short spoken walkthrough
Fictional example
- Candidate
- Costs are positive, so the cheapest network has no cycles. That makes it a minimum spanning tree with n − 1 roads, or no tree at all if the graph is disconnected.
- Candidate
- I'll sort the roads, scan from cheapest, and use union-find to accept a road only when it joins two different groups. I'll start a group counter at n and stop when it hits 1.
- Candidate
- If I run out of roads with more than one group left, I return -1. Sorting makes it O(m log m); union-find with path compression and union by size is nearly constant per call.
Related problems
Optimize Water Distribution in a Village is the same tree with a twist: each node can also be bought outright, which you model with an extra node. If you want to switch from greedy graphs to dynamic programming, Min Cost Climbing Stairs is the gentlest next step. The data structure interview questions page covers union-find and heaps in more depth.
How Natively fits into practice
Natively can look at a screenshot of a graph problem during a practice session and point to an approach, which is a quick way to sanity-check your own choice between Kruskal and Prim after you commit to one. It also records a transcript of mock rounds on your machine, so you can reread whether you mentioned the -1 case before coding. More on an AI interview assistant for Mac and Windows.
Questions people ask
What algorithm solves Connecting Cities With Minimum Cost?
A minimum spanning tree algorithm. Kruskal sorts the roads and uses union-find to add each road that joins two separate groups; Prim grows one tree with a min-heap. Both run in O(m log m).
When should the answer be -1?
When the roads cannot connect every city. In Kruskal, start a group counter at n and decrease it on each accepted road; if it never reaches 1, return -1.
Why does the greedy choice of the cheapest road work?
By the cut property, the cheapest road crossing any split of the cities into two sides belongs to some minimum spanning tree, and Kruskal only accepts roads that cross between separate groups.
Can Dijkstra solve this problem?
No. Dijkstra finds shortest paths from one start city, which can cost more in total than the cheapest network that connects everyone. You need a spanning tree algorithm.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
