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?- A. 4 2
- B. 3 0
- C. 5 0
- 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
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…
- Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain…
- Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total…