Minimum Flips to Join Two Islands
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an R x C grid of integers containing only 0 (water) and 1 (land), two land squares belong to the same island whenever a path of orthogonally adjacent land squares (up, down, left, or right; never diagonal) joins them. The input map always contains exactly two distinct islands.
In one operation, you can turn any single water square (0) into land (1). Compute and return the smallest number of water squares that must be converted so both islands merge into one orthogonally connected landmass.
Examples
Example 1
Input:
grid = [
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]
]
Output: 3
Explanation: One island occupies (0, 0) and (0, 1), while the second sits at (2, 3). Converting the three water squares (0, 2), (1, 2), and (2, 2) (among several equal-length routes) joins (0, 1) to (2, 3), and no two-square conversion can reach across both the two-row and two-column gap.
Example 2
Input:
grid = [
[0, 1, 1],
[1, 0, 0],
[1, 0, 0]
]
Output: 1
Explanation: Because diagonal neighbors do not touch, [(0, 1), (0, 2)] and [(1, 0), (2, 0)] are separate islands even though (0, 1) and (1, 0) meet at a corner. Converting (0, 0) (or (1, 1)) links both islands with just 1 operation.
Example 3
Input:
grid = [
[1],
[0],
[0],
[0],
[0],
[1]
]
Output: 4
Explanation: In this single-column map, four water squares sit between (0, 0) and (5, 0). Every intermediate cell must become 1, requiring 4 conversions.
Constraints
1 <= R, C <= 200, whereR = len(grid)andC = len(grid[0]).- Every entry
grid[r][c]is either0or1. gridcontains exactly two 4-directionally connected components of1s.
Step-by-step walkthrough
Restate the problem
We are given an
R × Cgrid of0s (water) and1s (land) containing exactly two islands. Two land cells belong to the same island when you can walk between them using 4-directional steps (up, down, left, right—diagonals do not connect).We want the minimum number of
0cells we must convert to1so both islands merge into one connected landmass:Input grid: Convert three '0' cells (marked *): 1 1 0 0 1 1 * 0 0 0 0 0 ---> 0 0 * 0 --> 3 conversions join the islands 0 0 0 1 0 0 * 1Because the two islands start separate, they never share a 4-directional edge, so the answer is always at least
1.Brute force first: closest pair of land cells
Suppose we collect every
(r, c)cell of Island 1 into listAand every cell of Island 2 into listB. Walking along grid edges betweena = (r1, c1)andb = (r2, c2)takes at least|r1 - r2| + |c1 - c2|steps, which passes through|r1 - r2| + |c1 - c2| - 1intermediate cells.Because there are no obstacles and no third island, the closest pair
(a, b)always has pure water along any shortest grid walk between them (if a land cell sat in between, it would belong to Island 1 or Island 2 and form an even closer pair!). So the exact answer is:minimum over all a in A, b in B of (|r1 - r2| + |c1 - c2| - 1)Why not stop here? On a
200 × 200grid split down the middle by one column of water,|A|and|B|are each around20,000cells. Checking|A| × |B| ≈ 400,000,000pairs in Python is far too slow.Key idea: grow Island 1 outward one water ring at a time
Instead of pairing cells across the two islands, treat all of Island 1 as a single starting region at flip cost
0, and expand outward through water one layer at a time using multi-source breadth-first search (BFS)—a BFS whose queue initially holds every cell of Island 1:Start (Island 1 = 0, Island 2 = #): Layer 1 (cost 1): Layer 2 (cost 2): Layer 3 (cost 3): 0 0 . . 0 0 1 . 0 0 1 2 0 0 1 2 . . . . ---> 1 1 . . ---> 1 1 2 . ---> 1 1 2 3 . . . # . . . # 2 2 . # 2 2 3 [#] <-- hit!- Every cell of Island 1 starts in the queue with
flips = 0. - All water neighbors touching Island 1 enter the queue with
flips = 1. - Their unvisited water neighbors enter with
flips = 2, and so on.
Because a FIFO queue processes all cost-
kcells before any cost-(k + 1)cell, the very first time a cell at costklooks at a neighbor that is unvisited land (1), that neighbor belongs to Island 2 andkis guaranteed to be the minimum number of water cells we had to flip.- Every cell of Island 1 starts in the queue with
Phase 1: find and flood-fill Island 1 iteratively
First we scan the grid to find any one land cell
(start_r, start_c)—that cell belongs to Island 1. Then we run a flood fill (visiting every connected land cell of Island 1) so we can mark all of Island 1 withflips = 0and load all of its cells into our BFSqueue.Two engineering details matter here:
- Use an explicit
stacklist, not recursion. On a200 × 200grid, a winding snake-shaped island can contain20,000cells in a single chain, which would crash Python's default recursion limit of1,000. - Keep
flipsin a separateR × Ctable initialized to-1instead of overwritinggrid, so the caller's input list is never mutated.
from collections import deque # Four orthogonal step offsets: down, up, right, left. DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)] def find_first_land(grid: List[List[int]]) -> Tuple[int, int]: """Return (row, col) of the first land cell (value 1) in top-to-bottom reading order.""" rows = len(grid) cols = len(grid[0]) for r in range(rows): for c in range(cols): if grid[r][c] == 1: return r, c raise ValueError("grid contains no land cells")def shortest_bridge(grid: List[List[int]]) -> int: rows = len(grid) cols = len(grid[0]) # flips[r][c] stores: # -1 -> cell has not been visited yet # 0 -> cell belongs to Island 1 (zero flips needed to reach it) # k>0 -> water cell reachable from Island 1 by flipping k water cells flips = [[-1] * cols for _ in range(rows)] # Phase 1: flood-fill Island 1 iteratively (avoids recursion-depth crash on large grids) # and seed the BFS queue with every cell of Island 1 at cost 0. start_r, start_c = find_first_land(grid) flips[start_r][start_c] = 0 # stack: explicit DFS worklist of (row, col) land cells belonging to Island 1. stack = [(start_r, start_c)] # queue: FIFO deque of (row, col) cells ordered by increasing flip count. queue = deque() while stack: r, c = stack.pop() queue.append((r, c)) for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc in_bounds = 0 <= nr < rows and 0 <= nc < cols if in_bounds and grid[nr][nc] == 1 and flips[nr][nc] == -1: # Mark upon pushing so the same land cell is never pushed twice. flips[nr][nc] = 0 stack.append((nr, nc))Notice we set
flips[nr][nc] = 0when pushing ontostack, not when popping, so a cell with multiple land neighbors is never added twice.- Use an explicit
Phase 2: expand outward through water with BFS
Now
queueholds every cell of Island 1 atflips = 0, and every cell of Island 1 is already marked!= -1. We pop from the front ofqueueand inspect each in-bounds unvisited neighbor(nr, nc):- If
grid[nr][nc] == 1, it cannot be Island 1 (all of Island 1 already hasflips == 0), so we just reached Island 2! Since(nr, nc)is already land, we do not flip it—we returnflips[r][c], the count of water cells flipped to reach(r, c). - Otherwise
grid[nr][nc] == 0is water: flipping it costsflips[r][c] + 1, so we record that value and push(nr, nc)onto the back ofqueue.
# Phase 2: multi-source BFS outward across water, one ring of flipped water per layer. while queue: r, c = queue.popleft() for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc in_bounds = 0 <= nr < rows and 0 <= nc < cols if not in_bounds or flips[nr][nc] != -1: continue if grid[nr][nc] == 1: # All of Island 1 was already marked 0, so an unvisited 1 must be Island 2. # Stepping onto land needs no extra flip, so `flips[r][c]` is the exact answer. return flips[r][c] # Stepping into unvisited water flips one more water cell. flips[nr][nc] = flips[r][c] + 1 queue.append((nr, nc)) raise ValueError("grid does not contain a second island")- If
Trace Example 1 and Example 2 step by step
Example 1:
grid = [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]After Phase 1 (flood-fill Island 1 starting at (0, 0)): flips = [[ 0, 0, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]] queue = [(0, 0), (0, 1)] Layer 1 (pop cost-0 cells) -> water neighbors (1, 0), (1, 1), (0, 2) get cost 1: flips = [[ 0, 0, 1, -1], [ 1, 1, -1, -1], [-1, -1, -1, -1]] Layer 2 (pop cost-1 cells) -> water neighbors (2, 0), (2, 1), (1, 2), (0, 3) get cost 2: flips = [[ 0, 0, 1, 2], [ 1, 1, 2, -1], [ 2, 2, -1, -1]] Layer 3 (pop cost-2 cells) -> water neighbors (2, 2) and (1, 3) get cost 3: flips = [[ 0, 0, 1, 2], [ 1, 1, 2, 3], [ 2, 2, 3, -1]] Pop (2, 2) [cost 3] -> right neighbor (2, 3) has grid[2][3] == 1 and flips == -1! Return flips[2][2] = 3.Example 2:
grid = [[0, 1, 1], [1, 0, 0], [1, 0, 0]](diagonal corner touch)(0, 1)and(1, 0)touch only diagonally, so Phase 1 marks[(0, 1), (0, 2)]with0.- Popping
(0, 1)marks water neighbors(1, 1)and(0, 0)withflips = 1. - Later, popping
(1, 1)(or(0, 0)) sees unvisited land(1, 0)adjacent to it and returns1.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque # Four orthogonal step offsets: down, up, right, left. DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)] def find_first_land(grid: List[List[int]]) -> Tuple[int, int]: """Return (row, col) of the first land cell (value 1) in top-to-bottom reading order.""" rows = len(grid) cols = len(grid[0]) for r in range(rows): for c in range(cols): if grid[r][c] == 1: return r, c raise ValueError("grid contains no land cells") def shortest_bridge(grid: List[List[int]]) -> int: rows = len(grid) cols = len(grid[0]) # flips[r][c] stores: # -1 -> cell has not been visited yet # 0 -> cell belongs to Island 1 (zero flips needed to reach it) # k>0 -> water cell reachable from Island 1 by flipping k water cells flips = [[-1] * cols for _ in range(rows)] # Phase 1: flood-fill Island 1 iteratively (avoids recursion-depth crash on large grids) # and seed the BFS queue with every cell of Island 1 at cost 0. start_r, start_c = find_first_land(grid) flips[start_r][start_c] = 0 # stack: explicit DFS worklist of (row, col) land cells belonging to Island 1. stack = [(start_r, start_c)] # queue: FIFO deque of (row, col) cells ordered by increasing flip count. queue = deque() while stack: r, c = stack.pop() queue.append((r, c)) for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc in_bounds = 0 <= nr < rows and 0 <= nc < cols if in_bounds and grid[nr][nc] == 1 and flips[nr][nc] == -1: # Mark upon pushing so the same land cell is never pushed twice. flips[nr][nc] = 0 stack.append((nr, nc)) # Phase 2: multi-source BFS outward across water, one ring of flipped water per layer. while queue: r, c = queue.popleft() for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc in_bounds = 0 <= nr < rows and 0 <= nc < cols if not in_bounds or flips[nr][nc] != -1: continue if grid[nr][nc] == 1: # All of Island 1 was already marked 0, so an unvisited 1 must be Island 2. # Stepping onto land needs no extra flip, so `flips[r][c]` is the exact answer. return flips[r][c] # Stepping into unvisited water flips one more water cell. flips[nr][nc] = flips[r][c] + 1 queue.append((nr, nc)) raise ValueError("grid does not contain a second island")✅ Submit now — all tests should pass.
Intuition & how it works
Imagine dropping a custom mold shaped exactly like Island 1 into calm water so ripples spread outward from its entire shoreline at the exact same speed—one grid square per second. At t = 0, every land square of Island 1 is already dry. At t = 1, the ripple covers every water square touching Island 1 (meaning 1 flip reaches them). At t = 2, the ripple covers every water square two steps away (2 flips). The very first moment the expanding ripple touches any land square of Island 2, the number of water rings it crossed is the minimum number of water squares you need to flip.
Why not compare every land square of Island 1 against every land square of Island 2, or run a separate search from each shoreline cell? On a 200 × 200 grid divided by a narrow canal, each island can contain roughly 20,000 land squares, so comparing all pairs takes around 20,000 × 20,000 = 400,000,000 checks. Instead, we first run a flood fill (a graph traversal that visits every connected square of one region) to gather all squares of Island 1, and then run a single multi-source breadth-first search (BFS) (a level-by-level search that starts from many starting squares simultaneously in one shared FIFO queue, where first-in is first-out) so every square on the grid is visited at most once.
Walk through grid = [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]:
- Scanning from
(0, 0)finds the first1at(0, 0). Flood-filling from(0, 0)discovers Island 1 consists of(0, 0)and(0, 1), marks bothflips = 0, and seeds both into the queue. - Wave 1 pops the cost-
0cells and marks adjacent water squares(1, 0),(1, 1), and(0, 2)withflips = 1. - Wave 2 pops the cost-
1cells and marks unvisited water squares(2, 0),(2, 1),(1, 2), and(0, 3)withflips = 2. - Wave 3 pops the cost-
2cells and marks(2, 2)and(1, 3)withflips = 3. When(2, 2)(cost3) is popped next, its right neighbor(2, 3)is an unvisited1(Island 2!), so the search immediately returnsflips[2][2] = 3.
Complexity
- Time: O(R × C). Finding the first land square scans at most
R × Ccells. Both the iterative flood fill and the multi-source BFS mark a cell'sflipsentry the moment it is pushed, so each of theR × Ccells entersstackandqueueat most once and checks at most 4 neighbors inO(1)time. - Space: O(R × C). The
flipstable stores one integer per cell (R × Cintegers), andstackandqueueeach hold at mostR × Ccell coordinates at any time.
Edge cases
- Diagonally touching islands (
[[0, 1, 1], [1, 0, 0], [1, 0, 0]]): diagonals are not 4-directionally connected, so they form two distinct islands and converting one shared corner water square (1flip) joins them. - Single-row or single-column grids (
[[1], [0], [0], [0], [0], [1]]): neighbor bounds checks (0 <= nr < rows and 0 <= nc < cols) naturally keep the search inside the narrow strip and return4. - One island completely surrounding the other (ring around an inner island): if the outer ring is found first, BFS expands both outward to the border and inward across the lagoon until it touches the inner island.
- Closest bridge far from the first land cell found: because all cells of Island 1 enter
queueatflips = 0, an L-shaped island's far tip starts expanding at the exact same moment as its top-left cell. - Long snake-shaped island (~20,000 cells): using an explicit Python
liststack instead of recursion avoidsRecursionError(1,000-frame default limit). - Caller's input grid: storing distances in
flipsleavesgridcompletely untouched.
Common mistakes
- Using recursive DFS for the flood fill: hits Python's recursion limit on a
200 × 200grid when Island 1 snakes back and forth across thousands of cells. - Starting BFS from only
(start_r, start_c)instead of the whole first island: steps taken across Island 1's own land cells get counted as if they were water flips, overcounting whenever(start_r, start_c)is not on the closest shoreline. - Off-by-one on the return value: returning
flips[r][c] + 1when spotting Island 2 counts the destination land cell itself as a water flip; Island 2 is already land, soflips[r][c]is the exact answer. - Marking cells visited upon popping instead of upon pushing: allows the same water cell to be pushed into
queueup to four times by different neighbors, bloating memory and runtime. - Using
list.pop(0)instead ofcollections.deque.popleft():list.pop(0)shifts every remaining queue element inO(Q)time, degrading total time towardO((R × C)²).
Alternative approaches
- All-pairs Manhattan distance (
O(|A| × |B|)): Manhattan distance (the grid step distance|r1 - r2| + |c1 - c2|between two coordinates) minus1over all pairs(a, b)inIsland 1 × Island 2gives the exact answer because there are no obstacles or third islands, making it a great randomized test oracle on small grids, though too slow when both islands are large. - 0-1 BFS (
O(R × C)): 0-1 BFS (a shortest-path search on graphs whose edge weights are only0or1, pushing cost-0steps to the front of a deque and cost-1steps to the back) can start from(start_r, start_c)alone—walking across Island 1 at cost0and water at cost1until reaching a land cell at cost> 0—combining both phases into one loop at the expense of slightly trickier logic.
Follow-up questions
- How can you output the exact grid coordinates of the converted water cells instead of only their count? Store a
parenttable (parent[nr][nc] = (r, c)) whenever a water cell is first discovered in Phase 2. When(r, c)touches Island 2, followparentpointers backward from(r, c)until you hit a cell withflips == 0(Island 1); those intermediate coordinates are the exact water cells to convert, usingO(R × C)extra space. - How does the algorithm change if islands are connected across all eight directions, including diagonals? Replace
DIRECTIONSwith all 8 horizontal, vertical, and diagonal offsets in both the flood fill and the BFS. With 8 directions, a single step changes both row and column by 1, so the closest-pair distance changes from Manhattan distance to Chebyshev distancemax(|r1 - r2|, |c1 - c2|) - 1. - What if every water cell (r, c) has its own positive reclamation cost w[r][c] and you want the cheapest connecting path? Equal BFS layers no longer correspond to equal cost, so replace Phase 2's FIFO queue with Dijkstra's algorithm (a shortest-path search that uses a min-heap priority queue to always expand the lowest-total-cost cell first). Seed the min-heap with
(0, r, c)for every cell of Island 1 and addw[nr][nc]when stepping into water, running inO(R · C log(R · C))time.
Follow-up questions
- How can you output the exact grid coordinates of the converted water cells instead of only their count?
- How does the algorithm change if islands are connected across all eight directions, including diagonals?
- What if every water cell (r, c) has its own positive reclamation cost w[r][c] and you want the cheapest connecting path?
Similar questions
- Nearest Integer Value in a BST
- Dynamic Anagram Multiset with Largest-Group Queries
- Technical Deep Dive on a Defining Project
- Internal PKI and Mutual TLS Architecture
- Multi-Tenant Identity and Access Control Platform
- Scalable Resumable Video Upload and Processing Pipeline
More Coupang interview questions
- Dynamic Anagram Multiset with Largest-Group Queries Medium
- Signature Engineering Project: Impact, Lessons, and Hindsight Medium
- Technical Deep Dive on a Defining Project Medium Pro
- Internal PKI and Mutual TLS Architecture Medium Pro
- Multi-Tenant Identity and Access Control Platform Medium Pro
- Scalable Resumable Video Upload and Processing Pipeline Medium Pro
- Nearest Integer Value in a BST Easy Pro
- Monthly Cohort Retention Medium Pro
- Forecasting Next-Floor Elevator Demand Medium Pro
- Experiment Design for Dedicated Courier Elevators Medium Pro