Flip Isolated O Regions to X Using Union-Find
Data Structure DesignAuto-graded · 24 test casesLast updated
Implement a union-find solution to identify and capture O regions that don't reach the board's edges, testing disjoint-set design and 2D-to-1D index mapping.
You are given an m × n grid where each cell contains either 'X' or 'O'. Two 'O' cells belong to the same region when they are connected by a path of edge-adjacent 'O' cells (up, down, left, or right—diagonal connections do not count). A region is isolated if none of its cells appear on the grid's perimeter (that is, in row 0, row m-1, column 0, or column n-1).
Your task is to flip every cell in every isolated region from 'O' to 'X'. Regions that touch the perimeter remain unchanged.
Important: You must solve this problem using a union-find (disjoint-set) data structure. Flood-fill approaches (DFS or BFS) are not permitted for this exercise.
Return the modified grid after all isolated regions have been flipped.
Constraints
1 ≤ m, n ≤ 200m = len(board)andn = len(board[0])- Every row contains exactly
ncells - Each cell is either
'X'or'O'(single-character strings)
Rules
- Connectivity is strictly 4-directional (horizontal and vertical edges only)
'X'cells never change- An
'O'cell changes to'X'only when its entire region is isolated - You may modify the input grid in place, but must return the resulting grid with the same dimensions
Examples
Example 1
Input: flip_isolated_regions([['X', 'X', 'X', 'X', 'X'], ['X', 'O', 'O', 'X', 'X'], ['X', 'X', 'O', 'X', 'O'], ['X', 'O', 'X', 'X', 'X']])
Output: [['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'O'], ['X', 'O', 'X', 'X', 'X']]
Example 2
Input: flip_isolated_regions([['O', 'X', 'X'], ['X', 'O', 'X'], ['X', 'X', 'X']])
Output: [['O', 'X', 'X'], ['X', 'X', 'X'], ['X', 'X', 'X']]
Example 3
Input: flip_isolated_regions([['X', 'X', 'X', 'X', 'X'], ['X', 'O', 'O', 'O', 'X'], ['X', 'O', 'X', 'O', 'X'], ['X', 'O', 'O', 'O', 'X'], ['X', 'X', 'X', 'O', 'X']])
Output: [['X', 'X', 'X', 'X', 'X'], ['X', 'O', 'O', 'O', 'X'], ['X', 'O', 'X', 'O', 'X'], ['X', 'O', 'O', 'O', 'X'], ['X', 'X', 'X', 'O', 'X']]
Hints
Hint 1
Introduce a virtual sentinel node representing 'the perimeter' and union every border O cell with it.
Hint 2
Map each grid cell (i, j) to a unique integer for use as a union-find node index.
Hint 3
After building the union-find structure, an O region is isolated if and only if its root differs from the sentinel's root.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that a region survives if and only if it contains at least one perimeter cell. Rather than marking each region individually, we can model this as a connectivity problem using union-find with a clever trick: introduce a virtual sentinel node that represents "connected to the perimeter."
Algorithm
-
Map cells to integers: Assign each grid cell
(i, j)a unique indexi * n + j. Reserve one additional node (indexm * n) as the sentinel. -
Build the union-find structure:
- Scan every cell in the grid
- For each
'O'cell:- If it lies on the perimeter (row 0, row m-1, column 0, or column n-1), union it with the sentinel
- If the cell directly below is
'O', union them - If the cell directly to the right is
'O', union them
- We only check down and right neighbors because each edge is encountered exactly once this way, and union is symmetric
-
Identify isolated regions:
- Find the root of the sentinel node
- Any
'O'cell whose root differs from the sentinel's root belongs to an isolated region - Flip those cells to
'X'
Why It Works
-
Union-find components match grid regions: We only union edge-adjacent
'O'cells, so two'O'cells share a root if and only if a 4-directional path connects them. Diagonal neighbors are never united. -
The sentinel captures perimeter connectivity: Every perimeter
'O'cell unions with the sentinel, and transitivity propagates this property to the entire region. A region touches the perimeter exactly when it shares the sentinel's root. -
The decision is per-region, not per-cell: Even if only one cell in a large region touches the perimeter, the entire region survives because all cells in the region share the same root.
Implementation Details
The find function uses path halving (pointing each node at its grandparent during traversal) to keep tree height logarithmic. This is essential for a 200×200 grid (40,000 nodes), where deep chains would cause stack overflow with naive recursion.
A subtle point: since union doesn't guarantee the sentinel remains its own root, we must compare against find(sentinel), not sentinel itself.
Complexity
-
Time: O(m·n·log(m·n)) worst-case with path halving alone. Each cell performs at most 3 unions during construction and 1 find during the flip phase. With union-by-rank added, this improves to O(m·n·α(m·n)), which is effectively linear (where α is the inverse Ackermann function).
-
Space: O(m·n) for the parent array (m·n + 1 entries) and O(m·n) for the output grid copy.
Edge Cases
- Single row or column: Every cell is on the perimeter, so nothing changes
- All X cells: No unions occur; grid returned unchanged
- All O cells: Everything connects to the sentinel; nothing flips
- Single isolated O cell: Forms its own component with a different root than the sentinel, so it flips
- Large region with one perimeter cell: The entire region survives due to transitivity
def flip_isolated_regions(board: list[list[str]]) -> list[list[str]]:
m = len(board)
n = len(board[0])
parent = list(range(m * n + 1))
sentinel = m * n # virtual node representing perimeter connectivity
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
def union(a, b):
root_a, root_b = find(a), find(b)
if root_a != root_b:
parent[root_a] = root_b
# Build the union-find structure
for i in range(m):
for j in range(n):
if board[i][j] != 'O':
continue
idx = i * n + j
# Union with sentinel if on perimeter
if i == 0 or j == 0 or i == m - 1 or j == n - 1:
union(idx, sentinel)
# Union with adjacent O cells (only check down and right to avoid duplicates)
if i + 1 < m and board[i + 1][j] == 'O':
union(idx, idx + n)
if j + 1 < n and board[i][j + 1] == 'O':
union(idx, idx + 1)
# Create result and flip isolated regions
result = [row[:] for row in board]
sentinel_root = find(sentinel)
for i in range(m):
for j in range(n):
if result[i][j] == 'O' and find(i * n + j) != sentinel_root:
result[i][j] = 'X'
return result