Data Structures & AlgorithmsHardProduct company OA

Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected 'O's first, then flip the rest.

Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected 'O's first, then flip the rest.
def capture(board):
    R, C = len(board), len(board[0]); b = [list(r) for r in board]
    st = [(i, j) for i in range(R) for j in range(C) if (i in (0, R - 1) or j in (0, C - 1)) and b[i][j] == "O"]
    while st:
        i, j = st.pop()
        if 0 <= i < R and 0 <= j < C and b[i][j] == "O":
            b[i][j] = "S"; st += [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
    return ["".join("O" if c == "S" else "X" for c in r) for r in b]
print(capture(["XXXX", "XOOX", "XXOX", "XOXX", "XOOX"]))
What is printed?
  1. A. ['XXXX', 'XXXX', 'XXXX', 'XXXX', 'XOOX']
  2. B. ['XXXX', 'XXXX', 'XXXX', 'XOXX', 'XOOX']
  3. C. ['XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX']
  4. D. ['XXXX', 'XOOX', 'XXOX', 'XOXX', 'XOOX']

Correct answer: B. ['XXXX', 'XXXX', 'XXXX', 'XOXX', 'XOOX']

Instead of testing every region for 'surrounded', start from border 'O's: the bottom-row cells (4,1), (4,2) are safe, and (3,1) is safe through them. The interior region (1,1), (1,2), (2,2) never reaches the border and is captured. Flipping only cells not on the border (the trap) would wrongly capture (3,1). O(R·C).

More Coding Interview Problems questions

Exams that ask this topic