Max Area of Island solution explained
Max Area of Island gives you a grid of land (1) and water (0) and asks for the size of the biggest group of land cells joined edge to edge. Walk the grid; whenever you reach land you have not seen, flood-fill that whole group with an iterative depth-first or breadth-first search, count its cells as you go, and keep the largest count. Each cell is handled a constant number of times, so it runs in O(rows × cols) time.
By Evin JohnPublished 10 min read
The task
Each cell of a rectangular grid holds 1 for land or 0 for water. Land cells that share a side belong to the same island; touching at a corner is not enough. An island's area is how many land cells it contains. Return the largest area in the grid, or 0 when the grid has no land at all.
1 1 0 0 0 0
1 1 0 0 1 0
0 0 0 1 1 1
0 1 0 0 1 0
0 0 0 0 0 0The square in the top left has area 4. The plus shape on the right has 5 cells: the center at row 2, column 4 and its four neighbors. The single cell at row 3, column 1 is an island of area 1. Notice that the square and the plus never touch, not even diagonally, but if they touched only at a corner they would still be separate.
Before coding, ask whether you may overwrite the grid, how large it can be, and whether diagonal neighbors count. The answers decide whether you keep a separate visited array, whether recursion is safe, and whether you loop over four or eight directions.
What this question checks
It is a small step up from counting islands: the search must now return a value instead of just marking cells. Interviewers watch how you carry that value. Some candidates keep a global counter they forget to reset between islands; others return the size from a recursive call and sum it correctly. It also shows whether you think about stack depth, because one big island turns a recursive fill into a very deep call chain.
A naive idea and why it is wasteful
You could start a fresh search from every land cell, with its own visited set, and record the size each search finds. That gives the right maximum, since every search from a cell measures exactly that cell's island. But an island of k cells gets measured k times at a cost of k each, so one big island costs O(k²), and an all-land grid costs O((rows × cols)²). Sharing one visited marker across all searches fixes it: once a cell belongs to a measured island, no later search starts there.
The linear solution: one flood fill per island
Scan the cells in order. Skip water and anything already visited. At an unvisited land cell, push it on a stack, mark it, and set the island's size to 0. While the stack has cells, pop one, add 1 to the size, and push each in-bounds neighbor that is land and not yet marked, marking it at the moment of the push. When the stack is empty, compare the size with the best so far. Marking at push time matters: if you mark at pop time, two neighbors can each push the same cell and it gets counted twice, which inflates the area.
def max_area_of_island(grid):
if not grid or not grid[0]:
return 0
h, w = len(grid), len(grid[0])
seen = [[False] * w for _ in range(h)]
best = 0
for sr in range(h):
for sc in range(w):
if grid[sr][sc] != 1 or seen[sr][sc]:
continue
seen[sr][sc] = True
stack, size = [(sr, sc)], 0
while stack:
r, c = stack.pop()
size += 1
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
best = max(best, size)
return bestfunction maxAreaOfIsland(grid) {
const h = grid.length;
if (h === 0 || grid[0].length === 0) return 0;
const w = grid[0].length;
const land = grid.map((row) => row.slice()); // leave the caller's grid alone
let best = 0;
const stack = [];
for (let sr = 0; sr < h; sr++) {
for (let sc = 0; sc < w; sc++) {
if (land[sr][sc] !== 1) continue;
land[sr][sc] = 0;
stack.push(sr * w + sc);
let size = 0;
while (stack.length > 0) {
const cell = stack.pop();
const r = Math.floor(cell / w);
const c = cell % w;
size++;
if (r > 0 && land[r - 1][c] === 1) { land[r - 1][c] = 0; stack.push(cell - w); }
if (r < h - 1 && land[r + 1][c] === 1) { land[r + 1][c] = 0; stack.push(cell + w); }
if (c > 0 && land[r][c - 1] === 1) { land[r][c - 1] = 0; stack.push(cell - 1); }
if (c < w - 1 && land[r][c + 1] === 1) { land[r][c + 1] = 0; stack.push(cell + 1); }
}
if (size > best) best = size;
}
}
return best;
}The JavaScript version sinks visited land to 0 in a copy, which doubles as the visited marker. If the interviewer says you may modify the input, drop the copy and save the extra memory. Packing a cell into one number avoids allocating a small array per push, which helps on big grids in JavaScript; in an interview, a pair is perfectly fine too.
A recursive version is shorter: size(r, c) returns 0 for water, out-of-range or visited cells, and otherwise marks the cell and returns 1 plus the sizes of its four neighbors. It is fine on small grids and many interviewers accept it. Just say that a solid region of a million cells would make a million nested calls, which overflows Python's default limit and many JavaScript engine stacks, and that the explicit stack avoids this.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| New search from every land cell, fresh visited set each time | O((R·C)²) worst case | O(R·C) |
| One fill per island, shared visited marker | O(R·C) | O(R·C) for the marker and the stack |
| Same, sinking land in the input | O(R·C) | O(R·C) worst case for the stack only |
| Flip one water cell (follow-up, labeled regions) | O(R·C) | O(R·C) for labels and sizes |
Follow-up: flip one water cell
A common extension: you may turn at most one 0 into a 1. What is the largest island you can make? Trying every flip and re-running the fill is O((R·C)²). The linear approach runs the fill once, giving each island an id and storing its size. Then, for each water cell, collect the distinct island ids among its four neighbors, add their sizes plus 1 for the flipped cell, and keep the best. Using distinct ids is the key detail: one island can touch the same water cell from two sides and must not be counted twice. If the grid has no water, the answer is the whole grid.
def largest_after_one_flip(grid):
h, w = len(grid), len(grid[0])
label = [[0] * w for _ in range(h)]
sizes = {}
next_id = 1
for sr in range(h):
for sc in range(w):
if grid[sr][sc] == 1 and label[sr][sc] == 0:
label[sr][sc] = next_id
stack, size = [(sr, sc)], 0
while stack:
r, c = stack.pop()
size += 1
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == 1 and label[nr][nc] == 0:
label[nr][nc] = next_id
stack.append((nr, nc))
sizes[next_id] = size
next_id += 1
best = max(sizes.values(), default=0)
for r in range(h):
for c in range(w):
if grid[r][c] == 0:
ids = {label[nr][nc] for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1))
if 0 <= nr < h and 0 <= nc < w and label[nr][nc]}
best = max(best, 1 + sum(sizes[i] for i in ids))
return bestOn the example grid, flipping row 1, column 2 touches only the square and gives 5. Flipping row 2, column 1 joins the square and the single cell: 4 + 1 + 1 = 6. Flipping row 3, column 3 touches the plus from above and from the right; counted once, that is 5 + 1 = 6, but counting the plus once per side would claim 11. The true best is 6. Working a case like this out loud shows the interviewer you see why the ids must be distinct.
Edge cases
- An empty grid or empty rows: return 0.
- No land anywhere: 0. All land: rows × cols.
- One row or one column, where half the neighbor checks fall outside the grid.
- Islands that meet only at a corner, which must stay separate.
- A very large solid island, to show the fill does not recurse per cell.
Where people slip
- Marking a cell at pop time, so the same cell is pushed and counted more than once.
- Keeping the size in a variable outside the loop and never resetting it for the next island.
- Returning the number of islands, or the total land, instead of the largest one.
- Reading grid[r − 1][c] before checking r > 0; in Python that quietly wraps to the last row.
- In the flip follow-up, adding the same island's size twice when it touches the water cell from two sides.
Explaining it in the room
Fictional example
- Candidate
- Each island is a connected component of land cells, and I want the biggest component, so I will flood-fill each one and count the cells it reaches.
- Candidate
- One visited grid is shared by all fills, so every cell is counted once overall. That keeps it linear in the grid size.
- Candidate
- I mark cells when I push them. If I waited until popping, two neighbors could both push the same cell and my area would be too big.
- Interviewer
- What if you could add one land cell?
- Candidate
- I would label every island and store its size, then for each water cell sum the sizes of the distinct islands around it, plus one.
Related problems
Flood fill also drives Surrounded Regions, where it starts from the border instead of from every cell, and Pacific Atlantic Water Flow, where it runs uphill from two coasts. Rotting Oranges uses a breadth-first version that tracks time as well as reach, and Clone Graph runs the same traversal on an explicit graph.
Natively during practice
Grid problems reward drawing, and talking through a drawing is a skill of its own. When you rehearse, Natively can read the grid problem from a screenshot on your Mac or Windows machine, propose the flood-fill approach with the mark-on-push detail, and transcribe your mock answer so you can see whether you mentioned stack depth before the interviewer had to ask. Read more about Natively for interviews.
Questions people ask
How do you solve Max Area of Island?
Scan the grid. At each land cell not yet visited, run a depth-first or breadth-first fill that marks every connected land cell and counts them. Keep the largest count; return 0 if there is no land.
What is the time complexity of Max Area of Island?
O(rows × cols). One shared visited marker means each cell is pushed and counted at most once across all fills. Extra space is O(rows × cols) in the worst case for the marker and the stack.
Is recursive DFS safe for Max Area of Island?
On small grids, yes. On a large solid island it makes one nested call per cell, which can exceed Python's default recursion limit or a JavaScript engine's stack. An explicit stack or queue avoids that.
How do you find the largest island after flipping one water cell?
Label every island once and store its size. Then for each water cell, add 1 to the sizes of the distinct islands on its four sides and keep the best. Distinct ids stop an island that touches from two sides being counted twice.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
