InterviewPrepKit

Home / Coding / Graphs

Max Area of Island

medium Original ↗
Solving tips
  • See the grid as a graph: each land cell links to its 4 orthogonal land neighbors and an island is a connected component; you want the largest component's size.
  • Scan every cell; on an unvisited 1, flood-fill (DFS/BFS) the whole island returning its cell count, and track the running max; O(m*n) time.
  • Mark cells visited by sinking them to 0 for O(1) extra space, or use a separate visited set if the input must stay intact.
  • Pitfall: connectivity is 4-directional only (no diagonals), and initialize best=0 so all-water returns 0 naturally.

Problem

You’re given an m × n binary grid where 1 is land and 0 is water. An island is a maximal group of 1-cells connected 4-directionally (up, down, left, right — not diagonally). The area of an island is its number of cells.

Return the area of the largest island. If there is no land at all, return 0.

Examples

  • grid = [[1,1,0],[1,0,0],[0,0,1]]3 — the top-left island has 3 cells; the lone cell bottom-right has area 1.
  • grid = [[0,0,0],[0,0,0]]0 — all water.
  • grid = [[1,1,1],[1,1,1]]6 — one island covering the whole grid.

Constraints

  • m == len(grid), n == len(grid[0]), 1 <= m, n <= 50.
  • Each cell is 0 or 1.

Think about it first

Hint 1 Think of the grid as a graph: each land cell is a node, with edges to its 4 orthogonal land neighbors. An island is a connected component; you want the size of the largest one.
Hint 2 Scan every cell. When you hit an unvisited 1, launch a DFS/BFS that floods the whole island, counting cells, and mark them visited so you never recount. Track the running maximum count.
Hint 3 "Visited" can be a separate set, or you can sink land as you go by writing 0 over each counted cell (destructive but O(1) extra space). Union-find is an alternative: union adjacent land cells and take the largest set size.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.