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

Exams that ask this topic