Surrounded Regions
Problem
You are given an m x n board of characters 'X' and 'O'. A group of 'O' cells that are connected orthogonally is captured if it does not touch the border of the board anywhere, meaning it is completely enclosed by 'X'. Capture every such group by flipping all of its cells to 'X', in place. Groups that include at least one border cell are left unchanged.
- The board has at least one cell and at most 300 rows and 300 columns.
- Cells are only
'X'or'O'. - Modify the board in place; return nothing.
Examples
- Board
becomesX X X X X X O X O O X O X X X X X O O X X X X X X
The vertical pair in column 1 and the horizontal pair in row 3 are enclosed and flip. The pair atX X X X X X X X O O X X X X X X X X X X X X X X X(1,3),(1,4)survives because(1,4)lies on the right edge. [["O","X","X"],["X","O","X"],["X","X","O"]]becomes[["O","X","X"],["X","X","X"],["X","X","O"]]. The centreOonly touches the cornerOs diagonally, which does not count, so it is captured while the corners stay.[["O","O","O"],["O","X","O"],["O","O","O"]]is unchanged: everyOis on the border.
Hints
- Instead of asking "is this region enclosed?", ask "which
Ocells can not be captured?" - Every uncapturable
Ois connected to a borderO. Start from the border. - Flood fill from every border
O, temporarily marking reached cells safe. Then rewrite the board: safe cells becomeO, all otherOs becomeX.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.