Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the number of distinct islands by shape in a grid (shapes match only by translation).
Problem: Count the number of distinct islands by shape in a grid (shapes match only by translation).
def distinct(g):
R, C = len(g), len(g[0]); seen = set(); shapes = set()
def dfs(r, c, r0, c0, cells):
if not (0 <= r < R and 0 <= c < C) or g[r][c] != 1 or (r, c) in seen: return
seen.add((r, c)); cells.append((r - r0, c - c0))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): dfs(r + dr, c + dc, r0, c0, cells)
for r in range(R):
for c in range(C):
if g[r][c] == 1 and (r, c) not in seen:
cells = []; dfs(r, c, r, c, cells); shapes.add(tuple(sorted(cells)))
return len(shapes)
print(distinct([[1, 1, 0, 1, 1], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 0, 0, 1, 0]]))What is printed?- A. 3
- B. 4
- C. 2
- D. 1
Correct answer: C. 2
Record each island's cells relative to its first (top-left-most scanned) cell. The top-left and bottom-left islands are both an 'Γ' shape (cells (0,0), (0,1), (1,0)); the top-right is a '7' shape ((0,0), (0,1), (1,1)), and the bottom-right is the Γ again. Two distinct shapes; rotations or reflections would be different shapes under this rule. O(R·C · log) with sorting.
More Coding Interview Problems questions
- Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values. python from…
- Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts. python def nice(a, k): cnt = {0: 1}…
- Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums). python from…
- Problem: Given n meetings with values, choose non-overlapping ones (end < next start) to maximise total value – weighted interval…
- Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or…
- Problem: Count the distinct BST shapes that store keys 1..n. python def shapes(n): dp = [1] + [0] n for k in range(1, n + 1): dp[k] =…