THN Interview Prep

695. Max Area of Island

At a Glance

  • Topic: graphs
  • Pattern: DFS / Backtracking
  • Difficulty: Medium
  • Companies: Amazon, Google, Meta, Microsoft, Apple
  • Frequency: High
  • LeetCode: 695

Problem (one-liner)

In a binary grid (0 water, 1 land), return the area (cell count) of the largest 4-connected island, or 0 if none.

Recognition Cues

  • Same as island DFS but accumulate size per component
  • Track running maximum

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Two-pass — label components then count — extra memory.
  • Optimal — DFS returns area for each flood — O(nm) time, O(nm) stack worst case.

Optimal Solution

Go

func maxAreaOfIsland(grid [][]int) int {
	rows := len(grid)
	cols := len(grid[0])
	best := 0

	var area func(row int, col int) int
	area = func(row int, col int) int {
		if row < 0 || col < 0 || row >= rows || col >= cols {
			return 0
		}
		if grid[row][col] == 0 {
			return 0
		}
		grid[row][col] = 0
		return 1 +
			area(row+1, col) +
			area(row-1, col) +
			area(row, col+1) +
			area(row, col-1)
	}

	for row := 0; row < rows; row++ {
		for col := 0; col < cols; col++ {
			if grid[row][col] == 1 {
				island := area(row, col)
				if island > best {
					best = island
				}
			}
		}
	}
	return best
}

JavaScript

function maxAreaOfIsland(grid) {
  const rows = grid.length;
  const cols = grid[0].length;
  let best = 0;

  function area(row, col) {
    if (row < 0 || col < 0 || row >= rows || col >= cols) {
      return 0;
    }
    if (grid[row][col] === 0) {
      return 0;
    }
    grid[row][col] = 0;
    return (
      1 +
      area(row + 1, col) +
      area(row - 1, col) +
      area(row, col + 1) +
      area(row, col - 1)
    );
  }

  for (let row = 0; row < rows; row += 1) {
    for (let col = 0; col < cols; col += 1) {
      if (grid[row][col] === 1) {
        best = Math.max(best, area(row, col));
      }
    }
  }
  return best;
}

Walkthrough

Pick each 1, DFS sums toggled cells; update best.

Invariant: Sum returned equals island size; zeros prevent revisits.

Edge Cases

  • No land
  • Entire grid land — full size

Pitfalls

  • Counting area without marking visited — infinite recursion

Similar Problems

Variants

  • Perimeter of island — different accumulation

Mind-Map Tags

#grid #dfs #area #connected-component

Last updated on

Spotted something unclear or wrong on this page?

On this page