Solve diameter and shortest bridge problems
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates proficiency with tree and graph data structures and traversal techniques, focusing on computing binary tree metrics and shortest-path distances in grid-based graphs.
Constraints
- 2 <= n <= 200
- grid is an n x n matrix of 0s and 1s
- grid contains exactly two islands
- Islands are connected 4-directionally
- Answer fits in a 32-bit integer
Hints
- Use DFS to find and mark all cells of the first island.
- Start a multi-source BFS from all marked cells to expand over water.
- The first time BFS reaches a land cell not marked as the first island, return the current distance.