Shortest Bridge

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an n x n binary grid where 1 is land and 0 is water. An **island** is a maximal group of land cells connected edge-to-edge (up, down, left, right). The grid contains **exactly two** islands. You may turn water cells into land. Return the minimum number of water cells you must flip so that the two islands become connected into one. Aim for O(n²) time.

Examples

Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
Output: 3
The corners are Manhattan distance 4 apart, so a bridge needs three water cells, e.g. (0,1), (0,2), (1,2).
Input: grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,0]]
Output: 2
Flipping (1,1) and (1,2) links cell (0,1) of the first island to cell (2,2) of the second.

Constraints

  • n == grid.length == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] is 0 or 1
  • There are exactly two islands

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems