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?
  1. A. [1, 2, 3, 4, 1, 1]
  2. B. [1, 1, 2, 3, 1, 1]
  3. C. [1, 1, 2, 3, 2, 2]
  4. 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

Exams that ask this topic