Largest Island Possible After Converting One Water Cell to Land
Last updated: November 29, 2026
Quick Overview
Given an n by n binary grid, you may change at most one 0 to 1. Return the size of the largest 4-connected island achievable.
0
0
0 solved
Given an n by n binary grid, you may change at most one 0 to 1. Return the size of the largest 4-connected island achievable.
An onsite question that punishes the brute force of flipping each water cell and re-running a flood fill. The Google interviewer is looking for island labeling with precomputed sizes, then an O(1) per-cell merge that avoids double counting the same island.
What the Interviewer Expects
- Label each island with an id and record its size
- For each water cell, sum sizes of distinct neighboring island ids plus one
- Use a set to avoid counting the same island twice
- Handle an all-land grid
- State O(n^2) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if you may flip up to k cells?
- Support queries that flip cells one at a time and report the largest island.
- What changes with 8-directional connectivity?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: n by n grid of 0/1.
- Flip at most one 0.
- Output: max island size after the flip....
High-Level Design
Brute force flips each of up to water cells and floods, . Instead, do one labeling pass: BFS every island, writing an id (starting at 2 so it does not collide with 0/1) into the cells an...