Magicsheet logo

Max Area of Island

Medium
91.6%
Updated 6/1/2025

Max Area of Island

What is this problem about?

The Max Area of Island problem provides a 2D binary grid where 1 represents land and 0 represents water. An "island" is a group of 1s connected 4-directionally (horizontal or vertical). The area of an island is the number of 1s it contains. Your goal is to find and return the maximum area of any single island in the grid. If there are no islands, return 0.

Why is this asked in interviews?

This is one of the most quintessential Graph Traversal questions asked in coding interviews. It is universally used as a baseline to verify that a candidate can write a standard Depth-First Search (DFS) or Breadth-First Search (BFS) over a matrix. It tests your ability to navigate a grid, respect boundaries, and keep track of visited state to prevent infinite loops.

Algorithmic pattern used

This problem relies entirely on the Depth-First Search (DFS) (or BFS) pattern. You iterate through every cell in the grid. When you encounter a 1 that hasn't been visited, you trigger a DFS to explore the entire island. The DFS explores the 4 adjacent cells, returning 1 + dfs(up) + dfs(down) + dfs(left) + dfs(right). As you visit land cells, you mutate them to 0 (or mark them in a visited set) so they aren't counted twice. You maintain a global maximum of the areas returned by these DFS calls.

Example explanation

Grid:

0 0 1 0
0 1 1 0
0 0 0 0
  • Iterate r=0, c=0 (0), r=0, c=1 (0).
  • r=0, c=2 is 1! Trigger DFS.
    • Mark (0, 2) as 0. Size = 1.
    • Explore Down: (1, 2) is 1. Mark as 0. Size = 2.
    • Explore Left from (1, 2): (1, 1) is 1. Mark as 0. Size = 3.
    • No more connected 1s. DFS returns 3. Global max = 3.
  • Resume grid iteration. Since we mutated the island to 0s, we won't trigger DFS on (1, 1) or (1, 2) again. The maximum area is 3.

Common mistakes candidates make

The most frequent mistake is forgetting to mark cells as visited during the traversal, causing the DFS to bounce back and forth between two adjacent 1s infinitely until a Stack Overflow occurs. Another common error is failing to check grid boundaries (r < 0 || r >= rows || c < 0 || c >= cols) before accessing grid[r][c], resulting in an IndexOutOfBoundsException.

Interview preparation tip

To master the Max Area of Island coding problem, memorize the standard matrix DFS template. Always write your boundary checks at the very beginning of the recursive function: if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == 0) return 0; By returning 0 for invalid or water cells, your recursive summing logic 1 + dfs() + dfs()... remains incredibly clean and readable.

Similar Questions