Your Dashboard
Interview Coaching
Learn
System Design
ML System Design
Code
Behavioral
Salary Negotiation
Interview Guides
Leetcode 827. Making A Large Island
Given an n×n binary grid where you can flip at most one 0 to 1, compute the largest possible 4-directional island size after the flip. Key idea: label connected components and their sizes, then for each 0 consider merging distinct neighboring islands (sum their sizes +1), with the all-ones grid as an edge case.
Asked at:
Meta
DESCRIPTION
Given an n×n binary grid where you can flip at most one 0 to 1, compute the largest possible 4-directional island size after the flip. Key idea: label connected components and their sizes, then for each 0 consider merging distinct neighboring islands (sum their sizes +1), with the all-ones grid as an edge case.
Input:
Output:
Explanation: Flip the 0 at position (0,1) or (1,0) to connect both islands. Result: one island of size 3
Constraints:
- n == grid.length
- n == grid[i].length
- 1 <= n <= 500
- grid[i][j] is either 0 or 1
Understanding the Problem
Let's understand what we're being asked to do. We have an n×n binary grid where each cell is either 0 (water) or 1 (land). An island is a group of 1s connected horizontally or vertically (4-directional).
For example, in the grid [[1,0],[0,1]], there are two separate islands (top-left and bottom-right), each of size 1. In [[1,1],[1,0]], there's one island of size 3 (the three connected 1s).
The twist: We can flip at most one 0 to 1. Our goal is to find the largest possible island size after this optional flip.
Key constraint: The grid is n×n (square), and 1 <= n <= 500.
Edge cases to consider: What if the grid is already all 1s? (can't flip anything, return n*n). What if flipping a 0 connects multiple separate islands? What if the grid is all 0s? (flip one 0 to get island of size 1).
Brute Force Approach
For each 0 cell in the grid, temporarily flip it to 1, then run a DFS/BFS to compute the size of the resulting island at that position. Track the maximum island size found across all flips. This approach is straightforward but inefficient because we recompute island sizes from scratch for every single 0 cell, leading to repeated work.
Start brute force: try flipping each 0 to 1
0 / 106
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n^4) For each of O(n^2) cells, we potentially run DFS that visits O(n^2) cells, resulting in O(n^4) time
Space Complexity: O(n^2) DFS recursion stack can go O(n^2) deep in worst case, plus visited array of size O(n^2)
Building Intuition
When we flip a 0 to 1, we're potentially merging multiple existing islands that are adjacent to that 0.
For example, if a 0 is surrounded by three different islands, flipping it would connect all three into one giant island. The key insight is: we need to know the size of each existing island and which islands are neighbors of each 0.
If we can label each island with a unique ID and store its size, then for any 0 cell, we can look at its 4 neighbors, identify which distinct islands touch it, and calculate: 1 + sum of sizes of distinct neighboring islands.
This transforms the problem from 'try flipping every 0 and recompute' (expensive!) to 'precompute island info once, then check each 0 in constant time' (efficient!).
Imagine coloring each island a different color (red, blue, green, etc.) and writing its size on each cell.
Now when you look at a water cell (0), you can see which colored islands touch it. If it touches red (size 5), blue (size 3), and green (size 2), flipping this water cell would create an island of size 1 + 5 + 3 + 2 = 11.
The 'coloring' step is about identifying connected components, and the 'checking water cells' step is about merging distinct neighbors.
Common Mistakes
Optimal Solution
First, label each connected component (island) with a unique ID and compute its size using DFS. Store this information in a map. Then, for each 0 cell, examine its 4 neighbors to identify which distinct islands touch it (using a set to avoid counting the same island multiple times). The potential island size from flipping this 0 is 1 + sum of distinct neighboring island sizes. Track the maximum across all 0 cells, and handle the edge case where the grid is already all 1s.
Start: Find largest island after flipping at most one 0 to 1
0 / 70
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n^2) We visit each cell once during DFS labeling (O(n^2)), then check each cell once to evaluate flips (O(n^2)), resulting in O(n^2) total time
Space Complexity: O(n^2) We store island labels in an n×n grid (O(n^2)), island sizes in a map (O(number of islands)), and DFS recursion stack (O(n^2) worst case)
What We've Learned
- Connected component labeling with metadata: When you need to merge or analyze groups in a grid, use DFS/BFS to label each component with a unique ID and store its size in a hashmap - this transforms an O(n²) merge query into O(1) lookup, enabling efficient "what-if" analysis without re-traversing.
- Neighbor deduplication with sets: When summing sizes of adjacent islands around a cell, use a set to track unique island IDs before summing - this prevents double-counting when the same island touches a cell from multiple directions (e.g., an L-shaped island touching from north and east).
- Two-phase grid processing pattern: Separate preprocessing (label all components) from query evaluation (test each flip) - this amortizes the cost of component discovery across all potential modifications, turning an O(n⁴) brute force into O(n²).
- All-ones edge case handling: Always check if the grid has no zeros at all before processing - return n² immediately, as the flip logic assumes at least one zero exists and will fail or return incorrect results on a completely filled grid.
- Island merging formula: For each zero cell, the potential island size is 1 (the flipped cell) + sum of unique neighboring island sizes - this captures the insight that flipping connects previously disconnected components through a single bridge point.
- Grid modification without mutation: Instead of actually flipping cells and recalculating, precompute all component metadata once and simulate flips through arithmetic - this read-only approach is faster, parallelizable, and easier to debug than repeatedly modifying state.
Related Concepts and Problems to Practice
medium
This problem is highly similar as it involves labeling connected components in a matrix using DFS/BFS, which is the core technique needed for Making A Large Island. It teaches the fundamental pattern of identifying and counting distinct islands (connected components) in a grid.
easy
Flood Fill introduces the basic matrix DFS traversal pattern needed for island problems. It teaches how to explore connected cells in a grid and mark visited regions, which is essential groundwork before tackling the more complex component labeling in Making A Large Island.
This lesson provides foundational understanding of how to perform DFS on matrix structures with 4-directional movement. It covers the core techniques for navigating grids and handling boundaries, which are essential prerequisites for solving Making A Large Island.
Test Your Understanding
Why is matrix the right data structure for this problem?
matrix provides the optimal access pattern
It's the only data structure that works
It's the easiest to implement
It uses the least memory
Select an answer to see the explanation
Question Timeline
See when this question was last asked and where, including any notes left by other candidates.
Early November, 2025
Meta
Mid-level
Late October, 2025
Meta
Staff
same question but instead of island, it's bomb.
Early October, 2025
Meta
Staff
Comments
Hello Interview Premium
Your account is free and you can post anonymously if you choose.