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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

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
connected components
labeling
grid
hash map
union-find
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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 n2n^2 water cells and floods, O(n4)O(n^4). 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...


Submit Your Answer
Markdown supported