Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the number of islands after each 'add land' operation on an initially all-water grid.
Problem: Count the number of islands after each 'add land' operation on an initially all-water grid.
def islands_online(R, C, ops):
p = {}; cnt = 0; out = []
def f(x):
while p[x] != x: p[x] = p[p[x]]; x = p[x]
return x
for r, c in ops:
if (r, c) in p: out.append(cnt); continue
p[(r, c)] = (r, c); cnt += 1
for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if (nr, nc) in p:
a, b = f((r, c)), f((nr, nc))
if a != b: p[a] = b; cnt -= 1
out.append(cnt)
return out
print(islands_online(3, 3, [(0, 0), (0, 1), (1, 2), (2, 1), (1, 1), (1, 1)]))What is printed?- A. [1, 2, 3, 4, 1, 1]
- B. [1, 1, 2, 3, 1, 1]
- C. [1, 1, 2, 3, 2, 2]
- D. [1, 1, 2, 3, 1, 2]
Correct answer: B. [1, 1, 2, 3, 1, 1]
Each new land cell starts as its own island, then merges with every distinct neighbouring island (each merge −1). (1, 1) touches three separate islands – {(0,0),(0,1)}, {(1,2)} and {(2,1)} – so 3 + 1 − 3 = 1. Re-adding existing land changes nothing. Near O(k α) for k operations versus O(k·R·C) with a fresh DFS each time.
More Coding Interview Problems questions
- Problem: Return the length of the shortest path that visits every node of a small undirected graph (start and end anywhere, edges…
- Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ +…
- Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h. python def rebuild(people)…
- Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel. python import…
- Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting…
- Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge. python from collections…