Making A Large Island solution explained

Making A Large Island gives you a square grid of land and water and lets you turn at most one water cell into land; return the size of the biggest island you can end up with. Label every island once with an id and record its size, then for each water cell add 1 to the sizes of the distinct islands touching it. That is two passes over the grid, so O(n²) time instead of the O(n⁴) you get by flipping and re-measuring.

By Published 9 min read

The problem, restated

You get an n by n grid where 1 is land and 0 is water, and land cells sharing a side belong to the same island. You may change at most one 0 into a 1. Return the size, in cells, of the largest island that can exist after that change. If you choose not to change anything, the largest existing island is the answer.

1 1 0 0        A A . .
0 0 0 1        . . . B
1 0 1 1        C . B B
1 0 0 0        C . . .
A 4 by 4 grid made up for this page, with three islands: A (top left), B (right) and C (bottom left).

Island A has 2 cells, B has 3, and C has 2. Flipping row 1, column 0 joins A and C into 2 + 2 + 1 = 5. Flipping row 2, column 1 joins C and B into 2 + 3 + 1 = 6, which is the best. Flipping row 1, column 2 touches B from two sides, but B still counts once, so that flip gives 3 + 1 = 4, not 7.

What the interviewer is listening for

The brute force is easy to describe, so the real test is whether you see the precomputation: island sizes do not change when you look at different water cells, so compute them once. After that, interviewers watch for two details: counting an island once even if it touches the cell twice, and handling a grid with no water.

Brute force: flip each zero and measure again

For every 0, set it to 1, find the biggest island with a full flood fill, then set it back. Start the answer from the biggest island with no flip, which covers grids that are all land. There are up to n² zeros and each measurement costs n², so the total is O(n⁴). For a 500 by 500 grid that is tens of billions of steps.

def largest_island_slow(grid):
    n = len(grid)
    def biggest(g):
        seen, best = set(), 0
        for r in range(n):
            for c in range(n):
                if g[r][c] == 1 and (r, c) not in seen:
                    seen.add((r, c))
                    stack, size = [(r, c)], 0
                    while stack:
                        cr, cc = stack.pop()
                        size += 1
                        for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
                            if 0 <= nr < n and 0 <= nc < n and g[nr][nc] == 1 and (nr, nc) not in seen:
                                seen.add((nr, nc))
                                stack.append((nr, nc))
                    best = max(best, size)
        return best
    best = biggest(grid)  # covers a grid with no water at all
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 0:
                grid[r][c] = 1
                best = max(best, biggest(grid))
                grid[r][c] = 0
    return best
Python brute force, useful as a test reference.

Label once, then score every zero

The pattern here is component labeling: give each connected group an id and keep a small table from id to size. Pass 1 walks the grid; each unlabeled land cell starts a flood fill that writes the same id into every cell of its island and counts them. Pass 2 visits each 0, gathers the ids of its up to four neighbors into a set, and scores the flip as 1 plus the sum of those islands' sizes. The best score over all zeros, or the largest island if there are no zeros, is the answer.

def largest_island(grid):
    n = len(grid)
    moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
    label = [[0] * n for _ in range(n)]  # 0 = water or not yet labeled
    sizes = {}
    next_id = 1
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 1 and label[r][c] == 0:
                label[r][c] = next_id
                stack, size = [(r, c)], 0
                while stack:
                    cr, cc = stack.pop()
                    size += 1
                    for dr, dc in moves:
                        nr, nc = cr + dr, cc + dc
                        if 0 <= nr < n and 0 <= nc < n 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)  # no water to flip: keep the biggest island
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 0:
                touching = set()
                for dr, dc in moves:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < n and 0 <= nc < n and label[nr][nc]:
                        touching.add(label[nr][nc])
                best = max(best, 1 + sum(sizes[i] for i in touching))
    return best
Python: island ids and sizes, then one look at each zero.
function largestIsland(grid) {
  const n = grid.length;
  const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  const inside = (r, c) => r >= 0 && r < n && c >= 0 && c < n;
  const label = grid.map((row) => row.map(() => 0));
  const sizes = [0]; // sizes[id] for id >= 1
  for (let r = 0; r < n; r++) {
    for (let c = 0; c < n; c++) {
      if (grid[r][c] !== 1 || label[r][c] !== 0) continue;
      const id = sizes.length;
      label[r][c] = id;
      const stack = [[r, c]];
      let size = 0;
      while (stack.length > 0) {
        const [cr, cc] = stack.pop();
        size++;
        for (const [dr, dc] of moves) {
          const nr = cr + dr, nc = cc + dc;
          if (inside(nr, nc) && grid[nr][nc] === 1 && label[nr][nc] === 0) {
            label[nr][nc] = id;
            stack.push([nr, nc]);
          }
        }
      }
      sizes.push(size);
    }
  }
  let best = 0; // all land: the biggest island is the answer
  for (const s of sizes) best = Math.max(best, s);
  for (let r = 0; r < n; r++) {
    for (let c = 0; c < n; c++) {
      if (grid[r][c] !== 0) continue;
      const touching = new Set();
      for (const [dr, dc] of moves) {
        const nr = r + dr, nc = c + dc;
        if (inside(nr, nc) && label[nr][nc] !== 0) touching.add(label[nr][nc]);
      }
      let total = 1;
      for (const id of touching) total += sizes[id];
      best = Math.max(best, total);
    }
  }
  return best;
}
JavaScript: the same two passes with an array of sizes.

The JavaScript version takes the maximum with a loop rather than Math.max(...sizes). A checkerboard grid has about n²/2 islands, and spreading that many values into one call can throw a RangeError; in our Node run, 180,000 values (a 600 by 600 checkerboard) was enough. A union-find over the land cells is a fine alternative for pass 1 if you prefer it: the root of each set acts as the id, and the set size is the island size.

Trace on the example

Pass 1 gives A id 1 with size 2, B id 2 with size 3, and C id 3 with size 2. In pass 2, row 0, column 2 sees only A, scoring 3. Row 1, column 0 sees A above and C below, scoring 5. Row 1, column 2 sees B to the right and B below, so the set holds one id and the score is 4. Row 2, column 1 sees C on the left and B on the right, scoring 6. No other zero does better, so the answer is 6.

Complexity

n by n grid
ApproachTimeExtra space
Flip each zero and re-measureO(n⁴)O(n²)
Label islands, then score each zeroO(n²)O(n²) for labels and sizes
Union-find for labels, then scoreO(n² · α(n²)), effectively O(n²)O(n²)
n by n grid. Scroll sideways on a small screen.

Edge cases

  • All land: there is no zero to flip, so return n². Starting the answer at 0 and only scoring zeros returns 0, which is wrong.
  • All water: any single flip gives an island of 1.
  • A zero surrounded by one island on all four sides: that island must be counted once.
  • A 1 by 1 grid: the answer is 1 whether the cell is land or water.
  • Very large islands: use an explicit stack or union-find, not deep recursion.

Common mistakes

  • Adding neighbor sizes without removing duplicate ids, which double counts an island that wraps around the cell.
  • Using the land value 1 as an island id, so the first island's label cannot be told apart from unlabeled land. Start ids at 2 if you write them into the grid itself.
  • Forgetting the plus one for the flipped cell.
  • Re-running a flood fill for every zero, which quietly brings back the slow version.

Follow-ups

  • You may flip up to k zeros. The one-flip trick no longer applies; this becomes a much harder search problem, and a good answer explains why the local scoring breaks.
  • Return which cell to flip. Keep the position with the best score alongside the score.
  • The grid is not square. Nothing changes except using separate row and column counts.
  • Diagonal neighbors join islands. Use eight moves in both passes.

How to explain it

Fictional example

Talking through the idea before coding
Candidate
If I flip a zero, the new island is that cell plus every island touching it. Island sizes do not depend on which zero I pick, so I compute them once.
Candidate
First pass: label every island with an id and store its size. Second pass: for each zero, collect the ids of its neighbors in a set so an island touching twice counts once, and add their sizes plus one.
Candidate
I start the answer at the biggest existing island in case there are no zeros. Both passes touch each cell a constant number of times, so it is O(n²).

Count Sub Islands carries a property through each island's flood fill instead of a size. Number of Islands is the plain labeling pass, and Shortest Bridge measures the gap between two islands instead of filling one cell. For a grid problem where the cost of moving matters, see Path With Minimum Effort. All walkthroughs are on the coding problems hub.

Practicing it with Natively

When you rehearse on Mac or Windows, Natively can pick up the grid from a screenshot and help you label the islands by hand before you code, which is where the double-counting bug is easiest to spot. It can also suggest an implementation once your plan is clear, and the session transcript and notes stay available so you can review how you explained the two passes. More on the AI interview assistant page.

Questions people ask

How do you solve Making A Large Island?

Label every island with an id and record its size. For each water cell, add 1 to the sizes of the distinct islands touching it. The best score, or the largest island if there is no water, is the answer.

Why use a set of island ids in Making A Large Island?

One island can touch the same water cell from two or more sides. A set makes sure its size is added once.

What is the time complexity of Making A Large Island?

O(n²) for an n by n grid: one pass to label islands and one pass over the water cells.

What if the grid has no water in Making A Large Island?

Then nothing can be flipped and the answer is the whole grid, n². Start the answer from the largest existing island to cover this.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP