Surrounded Regions solution explained

Surrounded Regions gives you a board of X and O cells and asks you to turn every O into X, in place, unless that O is connected through other O cells, up, down, left or right, to the board's edge. Flip the question around: flood-fill from every O on the border and mark what it reaches as safe, then sweep the board once, turning unmarked O cells into X and safe cells back into O. Every cell is touched a constant number of times, so it is O(rows × cols).

By Published 10 min read

What you are asked to do

The board is a grid of characters, each X or O. A region is a group of O cells joined through shared sides. A region is captured if none of its cells lie on the outer edge of the board, because then it is closed in by X cells on every side. Capturing means replacing all of its O cells with X. Change the board in place; there is nothing to return. Regions that touch the edge, even through one cell, are left alone.

before            after
X X X X X         X X X X X
X O O X X         X X X X X
X X O X O         X X X X O
X O X X O         X X X X O
X X X O X         X X X O X
A board drawn for this page, before and after

The three-cell region in the upper middle is enclosed, so it becomes X. The lone O at row 3, column 1 is enclosed too. The pair on the right edge survives, and so does the single O on the bottom edge. Note that diagonal contact does not connect cells: the O at row 3, column 1 touches the upper region only at a corner, which does not save it.

Ask before you start: may you modify the board in place (normally that is the point), can it be empty or a single row, and are diagonal links really ignored?

What the interviewer wants to see

Everyone can describe the capture rule. The signal is whether you flip the search direction. Trying to decide, for each region, whether it is enclosed leads to awkward code that has to finish exploring a region before it can act on it. Starting from the border makes every decision local and leaves a two-pass solution that is short enough to write without bugs. Interviewers also listen for the stack depth caveat, since large boards are a natural follow-up.

The slow way: test every O for an escape route

For each O, search through connected O cells and see whether any of them is on the edge. If none is, this O is captured. Flipping it right away would actually be safe, since removing a cell from an enclosed region never connects that region to the edge, but the reference below writes to a copy so it stays independent of the input it is checked against. Each search may cover the whole board, so this is O((R·C)²). A tidier version explores each region once, collects its cells and records whether any touched the edge, which is linear; but the border-first version below is shorter still and easier to get right.

def capture_slow(board):
    h = len(board)
    w = len(board[0]) if h else 0
    out = [row[:] for row in board]
    for r in range(h):
        for c in range(w):
            if board[r][c] != "O":
                continue
            seen, stack, escapes = {(r, c)}, [(r, c)], False
            while stack and not escapes:
                x, y = stack.pop()
                if x in (0, h - 1) or y in (0, w - 1):
                    escapes = True
                for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                    if 0 <= nx < h and 0 <= ny < w and board[nx][ny] == "O" and (nx, ny) not in seen:
                        seen.add((nx, ny))
                        stack.append((nx, ny))
            if not escapes:
                out[r][c] = "X"
    return out
Python reference: an escape search from every O. Returns a new board; used only for testing.

Border-first flood fill

Walk the four edges. For each O on an edge, start a flood fill that turns it and every O connected to it into a temporary marker, say S for safe. When all edges are done, every O still on the board is enclosed. Sweep the whole board once: an O becomes X, an S goes back to O, and X stays X. Two passes, no per-region bookkeeping.

def solve(board):
    if not board or not board[0]:
        return
    h, w = len(board), len(board[0])
    edge = [(r, c) for r in range(h) for c in (0, w - 1)]
    edge += [(r, c) for c in range(w) for r in (0, h - 1)]
    stack = []
    for r, c in edge:
        if board[r][c] == "O":
            board[r][c] = "S"
            stack.append((r, c))
    while stack:
        r, c = stack.pop()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < h and 0 <= nc < w and board[nr][nc] == "O":
                board[nr][nc] = "S"
                stack.append((nr, nc))
    for r in range(h):
        row = board[r]
        for c in range(w):
            row[c] = "O" if row[c] == "S" else "X"
Python: mark safe cells from the edges with an explicit stack, then sweep. Modifies the board in place.

Seeding the stack with all edge cells at once is the same multi-source idea used in Rotting Oranges, though here the order of visiting does not matter. The edge list repeats the corners; that is harmless, because a corner turned into S is no longer O and will not be pushed again. The final sweep can write X for everything that is not S, since an X stays X and an unmarked O must become X.

function solveBoard(board) {
  const h = board.length;
  if (h === 0 || board[0].length === 0) return;
  const w = board[0].length;
  const stack = [];
  const markSafe = (r, c) => {
    if (r < 0 || r >= h || c < 0 || c >= w || board[r][c] !== "O") return;
    board[r][c] = "S";
    stack.push([r, c]);
  };
  for (let r = 0; r < h; r++) { markSafe(r, 0); markSafe(r, w - 1); }
  for (let c = 0; c < w; c++) { markSafe(0, c); markSafe(h - 1, c); }
  while (stack.length > 0) {
    const [r, c] = stack.pop();
    markSafe(r + 1, c);
    markSafe(r - 1, c);
    markSafe(r, c + 1);
    markSafe(r, c - 1);
  }
  for (let r = 0; r < h; r++) {
    for (let c = 0; c < w; c++) board[r][c] = board[r][c] === "S" ? "O" : "X";
  }
}
JavaScript: the board is an array of character arrays, changed in place.

Putting the bounds and value checks inside markSafe keeps the main loop short and makes it hard to forget one. If you would rather not write a marker into the board, use a separate boolean grid for safe cells; it costs O(R·C) extra memory but leaves the board unchanged until the final sweep.

The union-find alternative

Give every cell an index and add one extra node that stands for the outside. Union each edge O with the outside node, and union each O with its O neighbors. Afterward, an O whose root differs from the outside node's root is enclosed. It is the same complexity in practice and more code, but it is a good answer if the interviewer asks how you would handle cells arriving one at a time, or if you already have a union-find structure written.

def solve_union_find(board):
    if not board or not board[0]:
        return
    h, w = len(board), len(board[0])
    parent = list(range(h * w + 1))
    outside = h * w

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a, b):
        ra, rb = find(a), find(b)
        if ra != rb:
            parent[ra] = rb

    for r in range(h):
        for c in range(w):
            if board[r][c] != "O":
                continue
            if r in (0, h - 1) or c in (0, w - 1):
                union(r * w + c, outside)
            if r + 1 < h and board[r + 1][c] == "O":
                union(r * w + c, (r + 1) * w + c)
            if c + 1 < w and board[r][c + 1] == "O":
                union(r * w + c, r * w + c + 1)
    safe_root = find(outside)
    for r in range(h):
        for c in range(w):
            if board[r][c] == "O" and find(r * w + c) != safe_root:
                board[r][c] = "X"
Python: disjoint sets with a virtual outside node at index h * w.

Complexity

R × C board
ApproachTimeExtra space
Escape search from every OO((R·C)²) worst caseO(R·C)
Border-first fill with a marker, then sweepO(R·C)O(R·C) worst case for the stack
Same, with a separate safe gridO(R·C)O(R·C) for the grid and stack
Union-find with an outside nodeNear O(R·C), with an inverse Ackermann factor if union by rank is addedO(R·C)
R × C board. Scroll sideways on a small screen.

Edge cases

  • Empty board or empty rows: do nothing.
  • One or two rows, or one or two columns: every cell is on the edge, so nothing is captured.
  • All O: everything touches the edge through its neighbors, so the board is unchanged.
  • An enclosed region next to a safe one, touching only at a corner: it is still captured.
  • A huge board of O cells, which a recursive fill from the edge would walk one call per cell.

Mistakes to avoid

  • Marking safe cells with a symbol the board already uses, so the final sweep cannot tell safe cells from enclosed ones.
  • Only seeding the fill from the top and left edges and forgetting the bottom and right.
  • Forgetting to turn the S markers back into O at the end.
  • Treating diagonal neighbors as connected.
  • Returning a new board when the task says to modify it in place, or the reverse.

How to present it

Fictional example

Turning the question around
Candidate
A region survives exactly when some cell of it is on the edge. So rather than asking whether each region is enclosed, I will find everything that is connected to the edge.
Candidate
I start a fill from every O on the four borders and mark those cells as safe with a temporary letter. Then one sweep: any O left is enclosed and becomes X, and the safe letters go back to O.
Candidate
Each cell is marked at most once and swept once, so it is linear. I am using a stack instead of recursion, because one large connected region would otherwise nest very deep.
Interviewer
Could you avoid writing the temporary letter?
Candidate
Yes, with a separate boolean grid, at the cost of extra memory. Or with union-find and a node that represents the outside.

Pacific Atlantic Water Flow uses the same start-from-the-edge reversal, twice. Max Area of Island runs the forward version of the flood fill. For something different, Palindrome Partitioning is a backtracking problem where the search explores choices instead of cells.

A note on Natively

The border-first idea clicks faster when you have to explain it to someone. In a practice run on Mac or Windows, Natively can pick up the board problem from a screenshot, suggest the edge-seeded fill and the final sweep, and give you a transcript of your explanation afterward, so you can see whether the reversal came across clearly. See the AI interview assistant page for more.

Questions people ask

How do you solve Surrounded Regions?

Flood-fill from every O on the four edges and mark those cells as safe. Then sweep the board: any O that was not marked is enclosed and becomes X, and the safe cells go back to O.

What is the time complexity of Surrounded Regions?

O(rows × cols). Each cell is marked at most once during the border fill and visited once in the final sweep. The stack can hold O(rows × cols) cells in the worst case.

Why start from the border instead of from each region?

A region survives exactly when it touches the edge, so everything reachable from the edge is safe and everything else is captured. Starting at the edge avoids deciding region by region and keeps the code short.

Can Surrounded Regions be solved with union-find?

Yes. Add a virtual node for the outside, union every edge O with it and every O with its O neighbors, then capture each O whose root is not the outside node's root.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP