Making A Large Island

Imagine you're a landscape architect designing the perfect archipelago! You have an n Ɨ n grid representing a map where 1s are land and 0s are water. Your goal is to create the largest possible island by converting at most one water cell into land.

An island is a group of land cells (1s) connected horizontally or vertically (4-directional). You need to find the size of the largest island you can create after making your strategic land conversion.

Key Challenge: You can only change one 0 to 1, so choose wisely! If the entire grid is already land, return n².

Input & Output

example_1.py — Basic Island Merge
$ Input: grid = [[1,0],[0,1]]
› Output: 3
šŸ’” Note: Changing either 0 to 1 connects the two separate islands (each of size 1) into one large island of size 3.
example_2.py — All Land Grid
$ Input: grid = [[1,1],[1,1]]
› Output: 4
šŸ’” Note: The entire grid is already one large island of size 4. No changes needed.
example_3.py — Strategic Placement
$ Input: grid = [[1,0,0,1,0],[1,0,1,1,1],[1,0,0,1,0]]
› Output: 6
šŸ’” Note: Changing the center water cell (1,2) to land connects multiple islands, creating the largest possible combined island.

Visualization

Tap to expand
šŸļø Strategic Island BuildingPhase 1: Survey & Label IslandsASize: 3BSize: 1CSize: 2Phase 2: Find Optimal BridgeABCšŸŒ‰Bridge connects A+BNew Size: 3+1+1 = 5šŸ’” Key Optimization InsightsšŸš€ Pre-computation: Label islands once, reuse sizes multiple timesšŸŽÆ Smart Lookup: Use Set to avoid counting same island twice⚔ Efficiency: O(n²) vs O(n⁓) brute force - 100x faster!🧠 Trade-off: Use extra space to save massive computation timeResult: Maximum island size after optimal bridge placement
Understanding the Visualization
1
Survey Phase
Map and label all existing islands with unique IDs
2
Catalog Phase
Record the population (size) of each island district
3
Planning Phase
For each potential bridge location, calculate total connected population
4
Optimization
Choose the bridge location that creates the largest connected region
Key Takeaway
šŸŽÆ Key Insight: Pre-labeling islands with unique IDs and caching their sizes transforms an O(n⁓) problem into an O(n²) solution by eliminating redundant calculations.

Time & Space Complexity

Time Complexity
ā±ļø
O(n⁓)

O(n²) water cells Ɨ O(n²) DFS for each cell

n
2n
āœ“ Linear Growth
Space Complexity
O(n²)

DFS recursion stack and visited array

n
2n
⚠ Quadratic Space

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 ≤ n ≤ 500
  • grid[i][j] is either 0 or 1
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 28
42.5K Views
High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen