KatInterview

Identify Connected Power Grid Regions

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsunion-findgraphsconnected-components

Last 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 station u and station v.
  • queries — a list of [a, b] pairs. For each query, you must report whether station a and station b are 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 ≤ 2000
  • 0 ≤ len(lines) ≤ 4000
  • 0 ≤ len(queries) ≤ 500
  • Each line [u, v] satisfies 0 ≤ u, v < n and u ≠ v. Duplicate lines may appear; treat them as one.
  • Each query [a, b] satisfies 0 ≤ a, b < n. A query where a == b is always True.
  • 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).