Number of Distinct Islands

Medium

Topics
ArrayHash TableDFSBFSUnion FindMatrix

You are given an m x n binary matrix grid. An island is a group of 1s connected 4-directionally (up, down, left, right). You may assume all four edges of the grid are surrounded by water.

Two islands are considered the same if one can be translated (slid horizontally and/or vertically) to equal the other. Rotations and reflections do not count as the same.

Return the number of distinct islands.

Example 1

01100011100020001130001101234
one island of each shapea shape already counted
Cells joined up, down, left or right form one island. Two islands count as the same when one can be slid onto the other, and the lighter cells mark islands whose shape had already appeared. 2 islands reduce to 1 distinct shape.
2D grid — one row per line.
Input:  grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Explanation: Both islands are 2x2 blocks, so sliding one onto the other matches it exactly.

Example 2

01101111000020000131101101234
one island of each shapea shape already counted
Two islands count as the same when one can be slid onto the other, and the lighter cells mark islands whose shape had already appeared. 4 islands reduce to 3 distinct shapes.
Input:  grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]]
Output: 3
Explanation: Four islands, but the horizontal pair in the top right and the horizontal pair in the bottom left are the same shape.

Example 3

00001000012
There is no land in this grid, so there is nothing to count and the answer is 0.
Input:  grid = [[0,0,0],[0,0,0]]
Output: 0
Explanation: No land at all.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Counting islands is the easy half — the hard half is deciding when two of them are the same island shape. Absolute coordinates cannot answer that, because the same shape in two places has two different coordinate sets.

What survives translation is the set of offsets within an island. Pin each island to its own top-left corner and every copy of that shape, wherever it sits in the grid, produces an identical set of offsets. So the question becomes: how many different offset sets are there?

Because only translation counts and not rotation, there is no need to try the eight orientations of each shape — one canonical form per island is enough.

Approach

  1. Sweep the grid. On each unvisited 1, collect the whole island’s cells and mark them visited so no cell is counted twice.
  2. Find the island’s minimum row and minimum column, and subtract them from every cell. That pins the island to the origin regardless of where it sat.
  3. Sort the resulting offsets so the same shape always yields the same sequence, and join them into one string key.
  4. Add each key to a set. The set’s size is the answer.

Walkthrough

grid = [[1,1,0,1,1],
        [1,0,0,0,0],
        [0,0,0,0,1],
        [1,1,0,1,1]]

island cells          min row/col   offsets (sorted)
(0,0)(0,1)(1,0)       0,0           (0,0)(0,1)(1,0)
(0,3)(0,4)            0,3           (0,0)(0,1)
(2,4)(3,3)(3,4)       2,3           (0,1)(1,0)(1,1)
(3,0)(3,1)            3,0           (0,0)(0,1)

keys seen: 3 distinct (rows 2 and 4 share one)
answer 3

Complexity

  • Time — O(m * n * log(m * n)): every cell is visited once, and each island’s offsets are sorted; across all islands that is at most one sort of every land cell.
  • Space — O(m * n): the visited matrix, plus the stored keys, which together hold at most one entry per land cell.

Common Pitfalls

  • Pinning to the first cell the traversal happens to reach rather than to the minimum row and column. Those differ when an island’s top row starts further right than a lower row, and the key then depends on where the sweep entered the island.
  • Leaving the offsets unsorted, which makes the key depend on traversal order — a depth-first and a breadth-first walk over the same shape would then disagree.
  • Treating diagonal neighbours as connected. The statement says 4-directionally, and allowing 8 merges islands that should stay separate.

Full Solution — all languages

class Solution:
    def numDistinctIslands(self, grid):
        rows, cols = len(grid), len(grid[0])
        seen = [[False] * cols for _ in range(rows)]
        shapes = set()
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] != 1 or seen[r][c]:
                    continue
                cells, stack = [], [(r, c)]
                seen[r][c] = True
                while stack:
                    y, x = stack.pop()
                    cells.append((y, x))
                    for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        ny, nx = y + dy, x + dx
                        if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == 1 and not seen[ny][nx]:
                            seen[ny][nx] = True
                            stack.append((ny, nx))
                base_r = min(y for y, _ in cells)
                base_c = min(x for _, x in cells)
                shapes.add(tuple(sorted((y - base_r, x - base_c) for y, x in cells)))
        return len(shapes)
SensAI
Beta
Tap the mic to stop voice mode