KatInterview

Flip Isolated O Regions to X Using Union-Find

Data Structure DesignAuto-graded · 24 test cases
MediumAuto-gradedData Structure Designunion-finddisjoint-setgrid

Last 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 ≤ 200
  • m = len(board) and n = len(board[0])
  • Every row contains exactly n cells
  • 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.