Katkat

Count distinct island shapes in a grid

TikTokSoftware Engineer · Technical Screen

Last updated

This problem tests grid traversal (DFS/BFS) and the ability to represent spatial structures in a canonical form to identify unique patterns.

Problem Statement

Given a 2D grid of 0s (water) and 1s (land), an island is a group of 1s connected 4-directionally. Two islands are considered the same if one island can be translated to match the other exactly (they have the same shape and size).

Write a function count_distinct_islands(grid) that returns the number of distinct island shapes in the grid.

Function Signature

def count_distinct_islands(grid: list[list[int]]) -> int:

Examples

Example 1: Input:

[[1, 1, 0],
 [1, 0, 0],
 [0, 0, 1]]

Output: 2 Explanation: The first island is defined by the shape of the top-left 1s; the second is a single 1 at the bottom right.

Example 2: Input:

[[1, 1, 0, 1, 1],
 [1, 0, 0, 1, 0]]

Output: 2 Explanation: Even though the islands are in different locations, the two shapes are structurally identical.

Constraints

  • grid dimensions are up to 50x50.
  • grid[i][j] is 0 or 1.

Edge Cases

  • Empty grid.
  • Grid with no land.
  • Grid where all land pieces are connected.

Implementation Details

To represent an island, you can record the path taken during a traversal (e.g., 'up', 'down', 'left', 'right') relative to the starting cell of that specific island. Ensure you mark visited cells to avoid counting them multiple times.

Hints

Hint 1

Perform a depth-first search (DFS) to explore every island you encounter.

Hint 2

For each island, track the sequence of moves (e.g., local coordinate offsets) relative to the island's starting point to create a 'shape signature'.

Hint 3

Store these signatures in a hash set to automatically deduplicate identical island shapes.

Follow-up questions

  • How would your approach change if islands could be rotated 90 degrees and still be considered the same?
  • What is the time and space complexity of your solution in terms of grid dimensions M and N?
  • Could you solve this using BFS instead of DFS, and what are the trade-offs in terms of memory usage for the recursion stack?