Fewest Cells to Fill to Join Two Separate Land Masses

Last updated: November 29, 2026

Quick Overview

A binary grid contains exactly two islands of 1s connected four-directionally. Return the minimum number of 0 cells that must be flipped to 1 to connect them.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A binary grid contains exactly two islands of 1s connected four-directionally. Return the minimum number of 0 cells that must be flipped to 1 to connect them.

A Meta onsite grid question that chains two traversals: one to label an island and one multi-source BFS to expand from it. It could be framed as connecting two map regions in a Meta Maps style tool. Interviewers check that you start the BFS from the whole island at once rather than from one cell.

What the Interviewer Expects
  • Find and mark the first island with DFS or BFS
  • Seed a BFS with every cell of that island at distance 0
  • Stop at the first cell belonging to the second island
  • Explain why multi-source BFS gives the minimum flips
  • Keep memory linear in grid size
Key Topics to Cover
Multi-source BFS
DFS
Connected components
Grid traversal
Shortest path
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 there were k islands and you wanted to connect them all cheaply?
  • How would you return which cells to flip?
  • What if flipping some water cells cost more than others?
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
  • Square or rectangular grid up to 100 x 100 with exactly two islands.
  • Flip water cells so that the islands touch four-directionally.
  • Return the minimum number of flips....
High-Level Design

The cost of connecting is the shortest grid distance between any cell of island A and any cell of island B, minus one. Collect island A with an iterative DFS, then run BFS starting from all its cells ...


Submit Your Answer
Markdown supported