There are n cities (0 .. n-1) and a list of direct roads between them. A province
is a group of cities connected directly or indirectly. Return the size of each province,
sorted ascending.
provinceSizes(n, roads)
Input format: n | roads, roads as a,b pairs. Output the sizes, sorted,
space-separated.
n=5, roads (0,1)(1,2)(3,4) // → [2, 3]
n=4, no roads // → [1, 1, 1, 1]
n=3, roads (0,1)(1,2)(0,2) // → [3]
A province is a connected component of the road network — cities linked directly or through a chain of roads. You need to identify these clusters and count each one's size. Union-find fits naturally: merge cities connected by roads, then tally sizes from the resulting groups.
You could build an adjacency structure and run BFS/DFS from every unvisited city, counting component sizes. That works, but union-find offers simpler bookkeeping: instead of walking edges city by city, just repeatedly merge each road's two endpoints, letting the structure track connectivity as a byproduct.
"Same root" is exactly equivalent to "connected by some path of roads," including multi-hop connections — path compression keeps root lookups fast even as merge chains pile up. A city with zero roads still contributes as its own province of size 1, since it stayed its own root — no special-case logic needed.
def province_sizes(n, roads):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in roads:
parent[find(a)] = find(b)
counts = {}
for i in range(n):
r = find(i)
counts[r] = counts.get(r, 0) + 1
sizes = list(counts.values())
sizes.sort()
return sizes
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.