17. Max Area of Island
mediumAsked at JetBrainsFind the largest connected island in a grid — JetBrains uses this to test whether you can attach an aggregator to a DFS traversal, the way their inspections sum metrics over PSI subtrees.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n binary grid, find the maximum area of an island. An island is land connected 4-directionally and its area is its cell count.
Constraints
1 <= m, n <= 50grid[i][j] is 0 or 1
Examples
Example 1
grid=[[0,0,1,0],[0,1,1,0],[0,0,0,0]]3Example 2
grid=[[0,0,0,0]]0Approaches
1. Repeated counting
After every flood, re-walk the entire grid; redoes work.
- Time
- O((m*n)^2)
- Space
- O(m*n)
// re-scan the grid for each new 1-cell start — inefficientTradeoff:
2. DFS with size accumulator
Walk every cell once. On a '1', DFS returns the size of the island while marking visited. Track the running max. Same accumulator pattern JetBrains uses to roll up metrics over PSI subtrees.
- Time
- O(m*n)
- Space
- O(m*n)
function maxAreaOfIsland(grid) {
const m = grid.length, n = grid[0].length;
const dfs = (i, j) => {
if (i<0||j<0||i>=m||j>=n||grid[i][j]!==1) return 0;
grid[i][j] = 0;
return 1 + dfs(i+1,j) + dfs(i-1,j) + dfs(i,j+1) + dfs(i,j-1);
};
let best = 0;
for (let i=0;i<m;i++) for (let j=0;j<n;j++)
if (grid[i][j]===1) best = Math.max(best, dfs(i,j));
return best;
}Tradeoff:
JetBrains-specific tips
JetBrains expects you to call out the DFS-with-accumulator pattern explicitly — the same recursive-visit pattern PSI inspections use to aggregate counts up the AST.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Max Area of Island and other JetBrains interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →