Making A Large Island

Hard

Topics
ArrayDFSBFSUnion FindMatrix

You are given an n x n binary grid. You may change at most one 0 to a 1. Return the size of the largest island (a 4-directionally connected group of 1s) achievable after at most one such change.

Example 1

01010101
the 0 to flipislands it joins
Flipping exactly one 0 can merge several islands at once. Flipping the shaded cell welds the shaded islands into one of size 3, the answer. The efficient version labels each island with a size once, then scores every 0 by the distinct labels around it.
2D grid — one row per line.
Input:  grid = [[1,0],[0,1]]
Output: 3

Example 2

01111001
the 0 to flipislands it joins
Input:  grid = [[1,1],[1,0]]
Output: 4

Example 3

01111101
islands it joins
Input:  grid = [[1,1],[1,1]]
Output: 4

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 500
  • grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The naive reading — flip each 0 in turn and recompute the largest island — is O(n⁴) and recomputes almost the same thing every time. The fix is to compute the island structure once.

Label every island with a unique id and record its size. Then each 0 is a cheap local query: look at its four neighbours, collect the distinct ids among them, and sum those sizes plus one for the flipped cell. Using ids rather than sizes is what makes deduplication possible — two neighbours of the same 0 often belong to the same island, and counting it twice is the classic error.

Ids start at 2 so they cannot be confused with the 0 and 1 already in the grid, which lets the grid double as the label array with no extra allocation.

Approach

  1. Flood fill each island with an explicit stack, assigning it an id from 2 upward and recording its size.
  2. Seed the answer with the largest existing island, which covers the case where there is no 0 to flip.
  3. For every 0, gather the distinct neighbouring ids, sum their sizes, add one, and keep the maximum.

Dry Run

grid      1 1 0
          1 0 0
          0 0 1

labelling pass
  island 2 = the four 1s at (0,0),(0,1),(1,0)   size 3
  island 3 = the single 1 at (2,2)              size 1

probing each 0
  (0,2)  neighbours: island 2 at (0,1)                  -> 3 + 1 = 4
  (1,1)  neighbours: island 2 at (0,1) and (1,0) -- the SAME island,
         counted once                                   -> 3 + 1 = 4
  (1,2)  neighbours: island 3 at (2,2)                  -> 1 + 1 = 2
  (2,0)  neighbours: island 2 at (1,0)                  -> 3 + 1 = 4
  (2,1)  neighbours: island 3 at (2,2)                  -> 1 + 1 = 2

answer 4

  all ones 3x3  -> 9   no 0 to flip, so the seed value wins
  all zeros 3x3 -> 1   flipping any single cell makes an island of one

Complexity

  • Time — O(n²): the labelling pass touches each cell once, and the probing pass does four constant-time lookups per 0. Measured at 0.26s for a 500×500 checkerboard, which is the worst case for island count.
  • Space — O(n²) for the explicit flood-fill stack in the worst case of one giant island, plus the size map. The grid itself carries the labels, so no separate label array is needed.

Common Pitfalls

  • Counting a neighbouring island twice. The (1,1) row above is the case: two of its neighbours belong to island 2, and summing both gives 7 instead of 4.
  • Recomputing island sizes per candidate 0, which is the O(n⁴) version and times out at n = 500.
  • Forgetting the all-ones grid, where no 0 exists and the answer is the existing largest island. Seeding the answer before the probe loop handles it.
  • Forgetting the all-zeros grid, where the answer is 1 rather than 0.
  • Labelling from 1 instead of 2, which collides with the grid's own land marker and makes the neighbour test grid[nr][nc] > 1 meaningless.
  • Recursing in the flood fill. At 500×500 a single component can be 250,000 cells deep; the shown solution uses an explicit stack for that reason.

Full Solution — all languages

class Solution:
    def largestIsland(self, grid):
        R = len(grid); C = len(grid[0])
        size = {}; idx = 2
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        def fill(sr, sc, iid):
            st = [(sr, sc)]; grid[sr][sc] = iid; cnt = 0
            while st:
                cr, cc = st.pop(); cnt += 1
                for dr, dc in dirs:
                    nr, nc = cr + dr, cc + dc
                    if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
                        grid[nr][nc] = iid; st.append((nr, nc))
            return cnt
        for r in range(R):
            for c in range(C):
                if grid[r][c] == 1:
                    size[idx] = fill(r, c, idx); idx += 1
        best = 0
        for v in size.values():
            if v > best: best = v
        for r in range(R):
            for c in range(C):
                if grid[r][c] == 0:
                    seen = set(); tot = 1
                    for dr, dc in dirs:
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] > 1:
                            pid = grid[nr][nc]
                            if pid not in seen: seen.add(pid); tot += size[pid]
                    if tot > best: best = tot
        return best
SensAI
Beta
Tap the mic to stop voice mode