FastPrepCapture Surrounded Regions with Union-Find

Capture Surrounded Regions with Union-Find

Apple logoApple● MediumFULLTIMEPHONE SCREEN

Problem statement

You are given a rectangular board as an array of equal-length strings board. Every character is either X or O.

A group consists of O cells connected through shared sides. Diagonal contact does not connect cells. A group is surrounded if none of its cells touches the outer edge of the board: the first or last row or column.

Replace every O in a surrounded group with X. Preserve all other characters and return the resulting row strings in the original row order. Do not change the input array.

Implement and use a disjoint-set union data structure, also called union-find. Do not solve the board with depth-first search or breadth-first search.

Function

captureSurroundedRegions(board: String[]) → String[]

Examples

Example 1

board = ["XXXX","XOOX","XXOX","XOXX"]return = ["XXXX","XXXX","XXXX","XOXX"]

The three connected interior O cells cannot reach a border and become X. The bottom-row O already touches the border and is preserved.

Example 2

board = ["OOOO","OXXO","OXOO"]return = ["OOOO","OXXO","OXOO"]

Every O belongs to a component that touches an outer row or column, so the board is unchanged.

Example 3

board = ["OXX","XOX","XXO"]return = ["OXX","XXX","XXO"]

Diagonal contact does not connect components. The center O is surrounded, while the two corner cells are on the border.

Constraints

  • 1 <= board.length <= 200.
  • 1 <= board[r].length <= 200 for every row r.
  • All rows have the same length.
  • Every character is the ASCII letter X or O.

More Apple problems

See Apple hiring insights
Saved
public String[] captureSurroundedRegions(String[] board) {
    // Write your code here.
}
board["XXXX","XOOX","XXOX","XOXX"]
expected["XXXX", "XXXX", "XXXX", "XOXX"]
Checking account…