Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island).
Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island).
from collections import deque
def bridge(g):
n = len(g); q = deque(); seen = set()
def dfs(r, c):
if not (0 <= r < n and 0 <= c < n) or g[r][c] != 1 or (r, c) in seen: return
seen.add((r, c)); q.append((r, c, 0))
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)): dfs(x, y)
dfs(*next((r, c) for r in range(n) for c in range(n) if g[r][c]))
while q:
r, c, d = q.popleft()
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < n and 0 <= y < n and (x, y) not in seen:
if g[x][y] == 1: return d
seen.add((x, y)); q.append((x, y, d + 1))
print(bridge([[1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]))What is printed?- A. 4
- B. 2
- C. 3
- D. 5
Correct answer: A. 4
The first island is {(0,0), (0,1), (1,0)}; the second is {(2,4), (3,3), (3,4), (4,4)}. The closest pair of cells across the islands, e.g. (0,1)–(2,4) or (1,0)–(3,3), is at Manhattan distance 5, so 4 water cells lie between them. Multi-source BFS from the whole first island finds this in O(n²): 4 flips.
More Coding Interview Problems questions
- Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall…
- Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS). python from functools import lrucache g = {0: [1, 2, 3], 1…
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…