HardArrayDepth-First SearchBreadth-First SearchUnion FindMatrixUpdated Sep 2026

827. Making A Large Island

Asked at Uber, TikTok, Anduril

Difficulty

Hard

Time

O(n^2)

Space

O(n^2)

Pattern

Array

Companies

3

Problem

You are given an n x n grid of 0s and 1s. A 1 is land, a 0 is water. An island is a group of 1s that are connected side-by-side (up, down, left, right — not diagonally).

You may flip at most one 0 into a 1. After that single change (or no change at all), return the size of the largest island in the grid. Size means the number of 1 cells in the island.

If the grid has no 0 at all, you cannot make any change, so the answer is the whole grid: n * n.

One flip can join islands

grid01011001Before: two islands of size 1 eachgrid01011101After flipping (0,1): all three 1s are now connected
The two 1s are diagonal, so they are separate. Flipping one 0 touches both and merges them into a size-3 island.

Constraints

  • ●n == grid.length
  • ●n == grid[i].length
  • ●1 <= n <= 500
  • ●grid[i][j] is either 0 or 1

Examples

Example 1
Inputgrid = [[1,0],[0,1]]
Output3
WhyThe two 1s are diagonal, so they are not connected yet. Flipping either 0 touches both of them, joining all three cells into one island of size 3.
Example 2
Inputgrid = [[1,1],[1,0]]
Output4
WhyThe three 1s already form one island. Flipping the 0 at the bottom-right connects it to that island, giving 4 cells.
Example 3
Inputgrid = [[1,1],[1,1]]
Output4
WhyThere is no 0 to flip, so the grid stays as it is. All four cells are one island, so the answer is 4.

Asked At

3 companies

How to Think About It

1

Brute force: for every 0 cell, temporarily set it to 1, run BFS/DFS to find the largest island, then revert. Track the maximum.

2

Optimize by precomputing island sizes. Use Union-Find or BFS to label each island and record its size.

3

For each 0 cell, check its 4 neighbors. Sum the sizes of distinct neighboring islands. Add 1 for the cell itself.

4

Use Union-Find with path compression and union by size to efficiently merge and query island sizes.

5

The answer is the maximum of (sum of distinct neighbor island sizes + 1) across all 0 cells. If no 0 exists, the answer is n*n.

Optimal Approach

First, label each connected component of 1s using BFS or Union-Find, recording the size of each component. Then, iterate over every 0 cell. For each 0, look at its 4 neighbors. Collect the sizes of distinct neighboring components (use a set of component IDs to avoid duplicates). The potential island size if we flip this 0 is the sum of those sizes plus 1. Track the global maximum. If there are no 0 cells, the answer is n*n. Union-Find with path compression and union by size gives near O(1) amortized operations.

Label islands, then test each 0

island id0101A00BStep 1 — Union-Find labels: A has size 1, B has size 1check cell (0,1)012011?1010Step 2 — neighbors of the 0 are A and B, two differentislandstotal = 1 + size(A) + size(B) = 1 + 1 + 1 = 3answer = max over all 0 cells
First give every island an id and a size. Then for each 0, add up the distinct island ids around it, plus 1 for the flipped cell.
ComplexityTime O(n^2)Space O(n^2)Every cell is scanned a constant number of times, and the Union-Find arrays hold one entry per cell.

What Trips People Up in Real Interviews

1

Ask whether changing a 0 is optional or required (it is optional — you may choose not to change any).

2

Clarify that diagonals do not count for connectivity.

3

Walk through the brute force first, then explain the precomputation optimization.

4

Be careful to avoid double-counting islands when a 0 cell borders the same island from multiple sides — use a hash set of island IDs.

5

Discuss time complexity: O(n^2) for Union-Find, O(n^2) for the final pass.

Solution Code

O(n^2) time
class Solution:
    def largestIsland(self, grid):
        n = len(grid)
        parent = list(range(n * n))
        size = [1] * (n * n)
        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x
        def union(a, b):
            ra, rb = find(a), find(b)
            if ra == rb: return
            if size[ra] < size[rb]:
                ra, rb = rb, ra
            parent[rb] = ra
            size[ra] += size[rb]
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 1:
                    for dr, dc in [(0,1),(1,0)]:
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
                            union(r * n + c, nr * n + nc)
        max_size = max(size) if any(grid[r][c] for r in range(n) for c in range(n)) else 0
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 0:
                    seen = set()
                    for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
                            seen.add(find(nr * n + nc))
                    total = 1 + sum(size[rid] for rid in seen)
                    max_size = max(max_size, total)
        return max_size if max_size > 0 else n * n

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Making A Large Island problem?

You are given an n x n binary matrix grid where 1 represents land and 0 represents water. You can change at most one 0 to a 1. After the change, find the size of the largest island (connected group of 1s). An island is formed by connecting adjacent cells horizontally or vertically.

How do you solve Making A Large Island?

The optimal approach runs in O(n^2) time and O(n^2) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Making A Large Island?

Making A Large Island is asked at Uber, TikTok, Anduril. It is a hard difficulty problem.

What are common mistakes on Making A Large Island?
  • Ask whether changing a 0 is optional or required (it is optional — you may choose not to change any).
  • Clarify that diagonals do not count for connectivity.
  • Walk through the brute force first, then explain the precomputation optimization.
  • Be careful to avoid double-counting islands when a 0 cell borders the same island from multiple sides — use a hash set of island IDs.
  • Discuss time complexity: O(n^2) for Union-Find, O(n^2) for the final pass.