Identify Connected Power Grid Regions
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests union-find (disjoint set union) to group transmission lines into connected components and answer queries about grid connectivity.
Identify Connected Power Grid Regions
A national grid operator models its power network as a set of stations numbered 0 through n - 1 and a list of transmission lines, each connecting two stations directly.
You are given:
n— the total number of stations.lines— a list of[u, v]pairs indicating a direct (bidirectional) transmission line between stationuand stationv.queries— a list of[a, b]pairs. For each query, you must report whether stationaand stationbare in the same connected region (i.e., reachable from each other through transmission lines).
Return a list of booleans, one per query, where True means the two stations are connected and False means they are not.
After answering the queries, also return the number of distinct connected regions in the grid.
The final return value is a dict with exactly two keys:
"answers"— the list of booleans (one per query, in order)."regions"— a single integer: the number of distinct connected regions.
Constraints
1 ≤ n ≤ 20000 ≤ len(lines) ≤ 40000 ≤ len(queries) ≤ 500- Each line
[u, v]satisfies0 ≤ u, v < nandu ≠ v. Duplicate lines may appear; treat them as one. - Each query
[a, b]satisfies0 ≤ a, b < n. A query wherea == bis alwaysTrue. - A station with no lines is its own region (isolated region).
Examples
Example 1
Input: grid_connectivity(6, [[0, 1], [1, 2], [3, 4]], [[0, 2], [0, 3], [3, 4], [5, 5]])
Output: {'answers': [True, False, True, True], 'regions': 3}
Example 2
Input: grid_connectivity(4, [], [[0, 1], [2, 3], [0, 0]])
Output: {'answers': [False, False, True], 'regions': 4}
Example 3
Input: grid_connectivity(5, [[0, 1], [1, 2], [2, 3], [3, 4]], [[0, 4], [1, 3], [2, 2]])
Output: {'answers': [True, True, True], 'regions': 1}
Hints
Hint 1
Use a Union-Find (Disjoint Set Union) structure: maintain a `parent` array where `parent[i]` is the representative of station `i`'s component, applying path compression and union by rank for near-O(1) per operation.
Hint 2
After processing all transmission lines with union operations, answering each query is a single `find(a) == find(b)` check.
Hint 3
Count distinct regions at the end by counting the number of nodes `i` where `find(i) == i` (i.e., they are their own root).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This problem is a textbook application of Union-Find (Disjoint Set Union, DSU). We need to:
- Merge stations joined by transmission lines into the same component.
- Answer "same component?" queries in near-constant time.
- Count how many components exist.
Algorithm
- Initialise
parent[i] = iandrank[i] = 0for all stations. Each station starts as its own root. - Union step — For every line
[u, v], callunion(u, v):- Find the roots of
uandv. - If different, attach the smaller-rank tree under the larger-rank root (union by rank). Tie-break: increment rank of the new root.
- Find the roots of
- Path compression —
find(x)uses path halving: on the way to the root it skips every other node, flattening the tree without a two-pass approach. - Query step — For each
[a, b], returnfind(a) == find(b). - Region count — A node
iis a root ifffind(i) == i. Count those.
Correctness
Union by rank ensures tree height stays O(log n). Path compression makes subsequent finds faster. Together they give the inverse-Ackermann α(n) amortised time per operation, which is effectively constant for all practical n.
Duplicate lines are harmless — union on two already-connected nodes is a no-op.
Self-queries (a == b) always return True because find(a) == find(a).
Complexity
| Time | Space | |
|---|---|---|
| Build | O((L + Q) · α(n)) | O(n) |
| Overall | essentially O(L + Q + n) | O(n) |
where L = number of lines, Q = number of queries, n = number of stations.
Reference Solution
from typing import List
def grid_connectivity(n: int, lines: List[List[int]], queries: List[List[int]]) -> dict:
parent = list(range(n))
rank = [0] * n
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(x: int, y: int) -> None:
rx, ry = find(x), find(y)
if rx == ry:
return
if rank[rx] < rank[ry]:
rx, ry = ry, rx
parent[ry] = rx
if rank[rx] == rank[ry]:
rank[rx] += 1
for u, v in lines:
union(u, v)
answers = [find(a) == find(b) for a, b in queries]
regions = sum(1 for i in range(n) if find(i) == i)
return {"answers": answers, "regions": regions}