Most likely not the most optimal solution but still runs in O(m⋅n) time. Didn’t want a solution for this, did it during a mock interview.
My Intuition
Find the valid regions
we can ignore the border elements when we search for regions since any “O” on the border cannot not be surrounded
valid region — define this as any region with no “O”s on the border
Alter the board of any valid region
from collections import deque
classSolution:defsolve(self, board: List[List[str]])->None: m_rows =len(board) n_cols =len(board[0]) seen =set()deffind_region(row, col): queue = deque() queue.append((row, col)) seen.add((row, col)) valid =True o_coords =[] directions =[(1,0),(0,1),(-1,0),(0,-1)]while queue: r, c = queue.popleft() o_coords.append((r, c))for dir_r, dir_c in directions: dr, dc = r + dir_r, c + dir_c
if(0<= dr < m_rows and0<= dc < n_cols and board[dr][dc]=="O"and(dr, dc)notin seen): queue.append((dr, dc)) seen.add((dr, dc))# on border (can't be valid region)if(0== dr or dr == m_rows -1or0== dc or dc == n_cols -1): valid =Falsereturn valid, o_coords
for row inrange(1, m_rows -1):for col inrange(1, n_cols -1):if board[row][col]=="O"and(row, col)notin seen: valid, output = find_region(row, col)if valid:for r, c in output: board[r][c]="X"