Making A Large Island (LeetCode 827): Solution and Explanation

Hard
Array
Depth First Search
Breadth First Search
Union Find
Matrix

Given an n x n grid of land (1) and water (0), you may turn at most one water cell into land. Return the area of the largest island you can end up with.

Intuition

Flipping one water cell can only glue together the islands that touch it. The new island is that cell plus every island sitting directly above, below, left or right of it.

Recomputing island areas after each possible flip would cost O(n^2) per flip. Instead, label every island once with its own id and remember its area. Then any water cell can be scored instantly from its four neighbours.

The one trap is counting the same island twice. If an island wraps around a water cell, two neighbours carry the same id, so collect distinct ids before adding areas.

Approach: Island ids plus a bridge test per water cell

  1. Scan the grid. At each unlabelled land cell, flood fill its island with a new id (starting at 2, so ids never clash with 0 and 1) and store size[id].
  2. Set best to the largest area, which is the answer when there is no water to flip.
  3. For each water cell, gather the distinct ids among its four neighbours.
  4. Its score is 1 plus the sum of those areas. Keep the maximum in best and return it.

Step-by-step example

grid = [[1,0],[0,1]]
  1. The cell (0,0) starts island 2 with area 1. The cell (1,1) starts island 3 with area 1.
  2. Without flipping, best = 1.
  3. Flip (0,1): its neighbours (0,0) and (1,1) belong to islands 2 and 3, so the score is 1 + 1 + 1 = 3. best = 3.
  4. Flip (1,0): the same two islands touch it, so the score is again 3.
  5. Return 3.

Code: Python, Java, C++

1class Solution:
2    def largestIsland(self, grid: List[List[int]]) -> int:
3        n = len(grid)
4        size = {}
5        label = 2
6        for r in range(n):
7            for c in range(n):
8                if grid[r][c] == 1:
9                    stack = [(r, c)]
10                    grid[r][c] = label
11                    area = 0
12                    while stack:
13                        x, y = stack.pop()
14                        area += 1
15                        for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
16                            if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 1:
17                                grid[nx][ny] = label
18                                stack.append((nx, ny))
19                    size[label] = area
20                    label += 1
21        best = max(size.values(), default=0)
22        for r in range(n):
23            for c in range(n):
24                if grid[r][c] == 0:
25                    seen = set()
26                    for nx, ny in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
27                        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] > 1:
28                            seen.add(grid[nx][ny])
29                    best = max(best, 1 + sum(size[i] for i in seen))
30        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Each land cell is painted exactly once, and each water cell looks at 4 neighbours.

Space

O(n^2)

The flood fill stack and the id-to-area map can grow to the number of cells.

Other approaches

Union-Find (time O(n^2 α(n)), space O(n^2))

Union every pair of adjacent land cells and keep component sizes at the roots. Then score each water cell from the distinct roots of its neighbours. Same complexity, a little more code.

Brute force flip and recount (time O(n^4), space O(n^2))

Try every water cell, flip it, and run a full flood fill to find the largest island. Simple, but O(n^4), far too slow for n = 500.

Common mistakes

  • Adding the same island twice when it touches the water cell from two sides. Deduplicate neighbour ids with a set.
  • Returning 0 for a grid that is all land. With no water to flip, the answer is n * n, so initialise best with the largest island.
  • Labelling islands with id 1, which cannot be told apart from unvisited land. Start ids at 2.
  • Recursive DFS on a 500 x 500 island can overflow the call stack in some languages. An explicit stack avoids it.

Frequently asked questions

Why start island ids at 2?

The grid already uses 0 for water and 1 for unvisited land. Writing ids 2, 3, ... into the grid marks cells as visited and records which island they belong to at the same time.

Do I have to flip a cell?

No, the flip is optional. That is why best starts at the largest existing island, which matters when the grid has no water.

Can a flipped cell join more than two islands?

Yes, up to four, one from each side. The score simply adds every distinct neighbouring island's area plus 1.