Max Area of Island

MediumGraphsdfs grid

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a 2D grid grid of size m x n, where each cell holds either 0 (water) or 1 (land). An **island** is a group of 1 cells that are connected to each other **4-directionally** (up, down, left, and right). You may assume every cell outside the grid's borders is water, so islands never wrap around the edges. The **area** of an island is simply the number of land cells (1s) that make up that island. Return the **maximum area** of any island in grid. If the grid contains no land at all, return 0.

Examples

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
The largest island is the connected block of land cells in the lower-left/center region, which totals 6 cells. No other island is bigger.
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
There is no land anywhere in the grid, so the maximum island area is 0.
Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 9
Every cell is land and they are all connected, forming a single island of area 9.

Constraints

  • `m == grid.length`
  • `n == grid[i].length`
  • `1 <= m, n <= 50`
  • Each `grid[i][j]` is either `0` or `1`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs grid problems