↓Skip to main content
  1. LeetCode/

LeetCode 827: Making A Large Island

·3 mins· ·
LeetCode Hard Dfs Bfs Matrix Union-Find
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-10-17

  • Submissions: Accepted ×2 (recursive DFS) → Accepted (iterative rewrite)

Approach
#

Flip at most one 0 to 1 and report the size of the largest island.

Brute force flips every 0 and recomputes the largest island, O(n^4), too slow.

Precompute island information instead:

  1. First pass: label each island (starting at 2, so labels never clash with 0 and 1), rewrite its cells with the label, and record each label’s size in a dict.
  2. Second pass: for each 0, look at the islands its four neighbors belong to, deduplicate with a set, add their sizes, and add 1 for the cell itself.

If the grid has no 0 at all, the answer is the size of that single island.

My Solution
#

class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        n = len(grid)
        size = {}
        label = 2
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))

        for r in range(n):
            for c in range(n):
                if grid[r][c] != 1:
                    continue
                grid[r][c] = label
                stack, count = [(r, c)], 1
                while stack:
                    x, y = stack.pop()
                    for dx, dy in dirs:
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 1:
                            grid[nx][ny] = label
                            count += 1
                            stack.append((nx, ny))
                size[label] = count
                label += 1

        best = max(size.values(), default=0)
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 0:
                    labels = {grid[r + dr][c + dc] for dr, dc in dirs
                              if 0 <= r + dr < n and 0 <= c + dc < n and grid[r + dr][c + dc] > 1}
                    best = max(best, 1 + sum(size[l] for l in labels))
        return best

The first version labeled islands with a recursive DFS; with n = 500, an island can have 2.5 * 10^5 cells and the recursion may go too deep. The third version switched to an explicit stack.

Complexity
#

Time O(n^2), space O(n^2).

Mistakes to Avoid
#

  • Adding the same island twice when two neighbors belong to it: always deduplicate labels with a set.
  • Starting labels at 1: they mix with the original land value 1, so labeled and unlabeled cells look the same.
  • Forgetting the all-ones grid: with no 0 to flip, the answer is the whole island’s size.

Interview Explanation
#

In one pass I label each island starting from 2 and record each label’s size. Then for every 0, I collect the island labels of its four neighbors, deduplicate them with a set, and add their sizes plus 1, which is the island formed by flipping that cell. The answer is the maximum over all zeros, also covering the all-land case. Two passes, O(n^2) time.

Related

LeetCode 864: Shortest Path to Get All Keys
·3 mins
LeetCode Hard Bfs Bit-Manipulation Matrix
LeetCode 864 note: the BFS state is (position, bitmask of keys), so the same cell with different keys is a different node
LeetCode 980: Unique Paths III
·2 mins
LeetCode Hard Backtracking Matrix Dfs
LeetCode 980 note: grid backtracking that marks visited cells in place and checks at the end that every empty cell was covered
LeetCode 3203: Find Minimum Diameter After Merging Two Trees
·3 mins
LeetCode Hard Tree Bfs Dfs Graph Tree-Diameter
LeetCode 3203 note: connect the two centers; the answer is max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1)
LeetCode 1210: Minimum Moves to Reach Target with Rotations
·3 mins
LeetCode Hard Bfs Matrix
LeetCode 1210 note: the BFS state is (tail position, orientation), each move checks its own empty cells, and equal step costs need no heap
LeetCode 323: Number of Connected Components in an Undirected Graph
·2 mins
LeetCode Medium Graph Dfs Bfs Union-Find
LeetCode 323 note: count components with DFS or Union-Find; Union-Find without path compression is much slower
LeetCode 1377: Frog Position After T Seconds
·3 mins
LeetCode Hard Tree Dfs Bfs Graph Probability
LeetCode 1377 note: undirected edges, seen must hold nodes, and an early arrival depends on whether the frog can still move