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?- A. ['XXXX', 'XXXX', 'XXXX', 'XXXX', 'XOOX']
- B. ['XXXX', 'XXXX', 'XXXX', 'XOXX', 'XOOX']
- C. ['XXXX', 'XXXX', 'XXXX', 'XXXX', 'XXXX']
- 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
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…