InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Max Area of Island

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug