Skip to main content

Making A Large Island - Solution & Explanation

HardArrayDepth-First SearchBreadth-First SearchUnion Find17 min readAsked at: Amazon, Microsoft, Meta +13
Practice this problem

Problem Statement

You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

Return the size of the largest island in grid after applying this operation.

An island is a 4-directionally connected group of 1s.

 

Example 1:

Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.

Example 3:

Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

 

Constraints:

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

Approach Overview

Problem Overview: You get an n x n binary grid where 1 represents land and 0 represents water. You may flip at most one 0 to 1. The task is to return the size of the largest island possible after the flip. An island is a group of 4-directionally connected land cells.

Approach 1: Brute Force Flip + DFS (O(n^4) time, O(n^2) space)

Iterate through every cell in the grid. Whenever you encounter a 0, temporarily flip it to 1 and run a full depth-first search to compute the size of the resulting island. Track the maximum size across all flips, then revert the cell back to 0. Each DFS may scan the entire grid (O(n^2)) and you potentially perform it for every cell (O(n^2)), resulting in O(n^4) time. This approach is straightforward but too slow for large grids.

Approach 2: DFS with Island Labeling (O(n^2) time, O(n^2) space)

The key insight is to pre-compute the size of every island so you never recompute it. Traverse the grid once and run DFS whenever you encounter an unvisited land cell. During the DFS, label the island with a unique id (for example 2, 3, 4...) and store its size in a hash map keyed by the island id. This step converts the grid into labeled components using DFS over the matrix.

Next, iterate over each 0 cell. Look at its four neighbors and collect the distinct island ids touching that cell. If you flip the cell to 1, the new island size becomes 1 + sum(sizes of unique neighboring islands). Use a set to avoid counting the same island twice. Track the maximum possible size while scanning all water cells. The grid traversal and labeling both take O(n^2), giving an optimal O(n^2) solution.

Approach 3: Union Find (Disjoint Set) (O(n^2) time, O(n^2) space)

You can also treat each land cell as a node in a disjoint-set structure and union adjacent land cells. The union operations build connected components representing islands. Each component stores its size. After building the structure, iterate through every 0 cell and inspect up to four neighboring components. Similar to the DFS labeling idea, combine the sizes of unique neighboring components plus one for the flipped cell. This approach relies on the Union Find data structure and performs nearly constant-time unions and finds with path compression.

Recommended for interviews: DFS with island labeling is the most common interview solution. It demonstrates strong grid traversal skills, component labeling, and efficient reuse of computed island sizes. Brute force shows basic reasoning but fails performance constraints. The labeled DFS approach reaches O(n^2) time and is easy to implement compared to Union Find while still demonstrating optimal thinking.

Approach 1: DFS with Island Labeling

This approach involves two main steps: firstly labeling all the islands in the grid using DFS, and secondly calculating the maximum possible island size by changing a '0' to a '1'.

1. Traverse the grid using DFS and label each island with a unique identifier. As you label the islands, keep track of the size of each island in a dictionary.

2. Iterate over each '0' cell in the grid, consider changing it to '1', and calculate the potential island size by inspecting neighboring cells.

3. Use a set to aggregate the neighboring island labels, and use the sizes from the dictionary to compute the total size.

This allows us to efficiently calculate the new island sizes by directly accessing individual island sizes using their labels.

This code begins by defining a helper function dfs to traverse and mark connected islands. Each cell is associated with a unique island index, and the area of each island is stored in a dictionary.

The main loop iterates through all grid cells. For '1' cells, DFS is executed, labeling the island and calculating its area. '0' cells are evaluated by looking at their surrounding areas to calculate their possible contribution to an enlarged island size.

Code

Python

Java

C++

Complexity

Time Complexity: O(n^2), because each cell of the grid is visited at most twice, once for DFS and once for change evaluation.

Space Complexity: O(n^2) for storage of the labeled grid and area dictionary.

Try this approach in the editor →

Approach 2: DFS

We can assign a unique identifier to each connected component, using an array p to record the connected component each position belongs to, i.e., p[i][j] represents the connected component number of (i, j). Use an array cnt to record the size of each connected component, i.e., cnt[root] represents the size of the connected component root.

First, we traverse the entire matrix. For each position grid[i][j] = 1 and p[i][j] = 0, we perform a depth-first search on it, mark its connected component as root, and count the size of the connected component.

Then, we traverse the entire matrix again. For each position grid[i][j] = 0, we find the connected components of the four positions above, below, left, and right of it, add up the sizes of these connected components, and add 1 for the current position, to get the maximum island area after changing the current position to 1.

The time complexity is O(n^2), and the space complexity is O(n^2). Where n is the length of the sides of the matrix.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
DFS with Island Labeling

Time Complexity: O(n^2), because each cell of the grid is visited at most twice, once for DFS and once for change evaluation.

Space Complexity: O(n^2) for storage of the labeled grid and area dictionary.

DFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Flip + DFSO(n^4)O(n^2)Conceptual starting point when first reasoning about flipping each water cell
DFS with Island LabelingO(n^2)O(n^2)Best practical solution for interviews and coding platforms
Union Find (Disjoint Set)O(n^2)O(n^2)Useful when practicing connectivity problems with dynamic component merging

Video Solution

G-52. Making a Large Island - DSU • take U forward • 168,609 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Making A Large Island easy or hard?
Making A Large Island is rated Hard on LeetCode because it combines matrix traversal, connected component labeling, and careful handling of duplicate neighboring islands. The optimal solution requires recognizing that island sizes must be precomputed.
How to solve Making A Large Island in O(n^2)?
Label every connected land component using DFS and assign it a unique id while recording its size in a map. For each 0 cell, gather the unique neighboring island ids and sum their sizes plus one for the flipped cell. This avoids recomputing island sizes and keeps the total work proportional to the grid size.
What is the best approach for Making A Large Island?
DFS with island labeling is the most common optimal solution. First label each island with a unique id and store its size using DFS in O(n^2). Then evaluate every 0 cell and combine the sizes of adjacent distinct islands to compute the largest possible island after one flip.
What data structure is used in Making A Large Island?
The most common solution uses DFS with a hash map to store island sizes and a set to avoid counting duplicate neighboring islands. Some implementations also use the Union Find (Disjoint Set) data structure to track connected components.
What is the time complexity of Making A Large Island?
The optimal solution runs in O(n^2) time for an n x n grid. One DFS pass labels every island and computes sizes, and a second pass evaluates each water cell by checking its four neighbors.
Making A Large Island Python or Java solution approach?
Python and Java implementations typically run a DFS to label islands and store their sizes in a dictionary or map. Then each 0 cell checks its four neighbors, combines distinct island sizes, and updates the maximum possible island area.
Is Making A Large Island asked at Google, Amazon, or Meta?
Making A Large Island is a classic grid connectivity problem and appears in interviews at companies that test graph and matrix traversal skills, including Google, Amazon, and Meta-style interview loops. It evaluates DFS/BFS reasoning and component merging logic.

Ready to solve this problem?

Practice Making A Large Island with our built-in code editor and test cases.

Practice on FleetCode