Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones − number of connected groups (union rows with columns).

Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones − number of connected groups (union rows with columns).
def removable(stones):
    p = {}
    def find(x):
        p.setdefault(x, x)
        while p[x] != x: p[x] = p[p[x]]; x = p[x]
        return x
    for r, c in stones: p[find(("r", r))] = find(("c", c))
    roots = {find(("r", r)) for r, c in stones}
    return len(stones) - len(roots)
print(removable([(0, 0), (0, 2), (1, 1), (2, 1), (2, 2), (3, 3)]), removable([(0, 0), (1, 1), (2, 2)]))
What is printed?
  1. A. 4 2
  2. B. 3 0
  3. C. 5 0
  4. D. 4 0

Correct answer: D. 4 0

Within a connected group (stones linked through shared rows or columns) you can always remove stones in leaf-first order until one remains, so the answer is n − groups. Treating each row and column as a node and each stone as an edge between them keeps union-find tiny. Group {(0,0), (0,2), (2,2), (2,1), (1,1)} and the lone (3, 3) → 6 − 2 = 4. Diagonal stones share nothing → 0. O(n·α).

More Coding Interview Problems questions

Exams that ask this topic