The Surrounded Regions interview question involves a 2D board containing 'X' and 'O' characters. Your task is to capture all regions that are "surrounded" by 'X'. A region is surrounded if it is completely enclosed by 'X's and does not have any path of 'O's that leads to the edge of the board. Capturing a region means changing all 'O's in that region to 'X's.
This is a classic "Medium" problem asked by almost every major tech company, including Apple, Microsoft, and Meta. It tests your knowledge of graph traversal algorithms like Breadth-First Search (BFS) or Depth-First Search (DFS). Specifically, it evaluates whether you can think "outside the box"—instead of finding surrounded regions directly, it's often easier to find the "not surrounded" regions (those connected to the boundary) and then flip everything else.
The primary algorithmic pattern is BFS/DFS on a Matrix or Union Find. The most efficient strategy is:
Board: X X X X X O O X X X O X X O X X
A frequent mistake is performing a DFS on every 'O' and trying to track if it hits a boundary. This can be complex and leads to redundant work. Another error is not handling the recursion depth in DFS, which can lead to stack overflow on very large boards (in such cases, BFS or iterative DFS is preferred).
For the Surrounded Regions coding problem, practice the "boundary traversal" technique. It’s a common pattern for matrix problems where edge cases dictate the solution. Also, familiarize yourself with the Union Find interview pattern, as it provides an alternative way to solve this problem by connecting nodes to a "dummy" boundary node.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Max Area of Island | Medium | Solve | |
| Number of Closed Islands | Medium | Solve | |
| Detect Cycles in 2D Grid | Medium | Solve | |
| Maximum Number of Fish in a Grid | Medium | Solve | |
| Number of Enclaves | Medium | Solve |