My first instinct was to BFS from every zero cell and count neighbors, which technically works but is way too slow on a 500x500 grid.
Use a two-pass approach: first label each existing island and compute its size using DFS/BFS. Then for each 0 cell, sum the sizes of distinct neighboring islands plus 1, and track the maximum; also consider the case where no flip is needed (if the matrix is all 1s or flipping doesn't increase the max).
Pro tip: Clarify edge cases upfront (e.g., all 1s, no 0s, multiple islands) and mention that you'd handle them gracefully; this shows attention to detail and prevents bugs in interviews.
Restate the problem: we can flip at most one 0 to 1, and we want the maximum connected island size. Consider edge cases: no 0s, all 1s, no 1s, and multiple islands.
Traverse the grid; for each unvisited 1, perform DFS/BFS to assign a unique island ID and record its size. Use a hash map to store island ID to size.
For each 0, look at its 4 neighbors; collect distinct island IDs and sum their sizes. The potential island size if flipping this 0 is sum + 1. Track the maximum.
If there are no 0s or if flipping any 0 doesn't increase the max (e.g., all 1s), the answer is the maximum island size found in step 2. Also consider if the grid has no 1s, then flipping one 0 gives size 1.
After evaluating all 0s, return the maximum of the best flip result and the original maximum island size.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.