Making a Large Island

hard

Given an n x n grid of 0s and 1s, you may change at most one 0 to a 1. Return the size of the largest island (4-directionally connected 1s) you can obtain. If the grid is already all 1s, the answer is the whole grid.

Hints

The value of flipping a 0 is 1 plus the sizes of the islands it connects.
Precompute island sizes with union-find so each flip is cheap.
A 0 can border the same island twice — dedupe neighbour islands by their root.

Common doubts

A single 0 may touch the same island on two sides; counting it twice would overstate the size.
The grid is already fully connected land, so the answer is the total number of cells.
It computes every island's size once; each flip then costs O(1) per neighbour instead of a full O(R·C) flood.

Interview follow-ups

The clean O(1)-per-flip trick breaks; you'd need search/DP over combinations.
Union and check the diagonal neighbours too.

Fun facts

  • LeetCode 827 — union-find with island sizes plus a neighbour-dedupe trick.
  • Labelling islands with sizes is a common preprocessing step for grid-flip problems.

Asked at

AmazonGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: grid = [[1,0],[0,1]]
Output: 3
Flipping a 0 joins the two size-1 islands into size 3.
Example 2
Input: grid = [[1,1],[1,1]]
Output: 4
Already one island of size 4; no flip needed.
Constraints

- 1 <= n <= 500 - grid[i][j] is 0 or 1

Solve this problem →