Skip to main content

Number of Distinct Islands II - Solution & Explanation

HardPremiumFree on FleetCodeHash TableDepth-First SearchBreadth-First SearchUnion Find6 min readAsked at: Amazon, Google
Practice this problem

Problem Statement

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).

Return the number of distinct islands.

 

Example 1:

Input: grid = [[1,1,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,1,1]]
Output: 1
Explanation: The two islands are considered the same because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.

Example 2:

Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.

Approach Overview

Problem Overview: You are given a binary grid where 1 represents land and 0 represents water. An island is a group of connected land cells. Two islands are considered the same if one can be rotated or reflected to match the other. The task is to count how many distinct island shapes exist under these transformations.

Approach 1: Pairwise Shape Comparison (Brute Force) (Time: O(I² * K), Space: O(I * K))

Run Depth-First Search to extract the coordinates of every island. Store each island as a list of relative positions from its starting cell. To determine if two islands are the same, generate all 8 transformations (4 rotations and their reflections) of one island and check if any match the other after normalization. This requires comparing each island with every previously found island. The approach works conceptually but becomes slow when many islands exist because every comparison requires transformation and coordinate matching.

Approach 2: Canonical Shape Hashing with DFS (Optimal) (Time: O(m * n * K), Space: O(m * n))

Traverse the grid and run DFS for every unvisited land cell. Record the island's coordinates relative to the origin cell. For that set of coordinates, generate the 8 possible transformations representing rotations and reflections. Normalize each transformation by shifting coordinates so the smallest x and y become zero, then sort the points and serialize them into a string. Choose the lexicographically smallest representation as the island's canonical form. Store this canonical shape in a hash table. Because every equivalent island produces the same canonical signature, duplicates collapse automatically. The number of unique signatures in the set is the answer.

The key insight is canonicalization. Instead of comparing islands against each other, convert every island into a transformation-invariant representation. DFS collects the structure, transformations normalize orientation, and hashing provides constant-time uniqueness checks. You could also explore component detection with Breadth-First Search, but DFS is typically simpler for collecting relative coordinates.

Recommended for interviews: The canonical hashing approach with DFS is the expected solution. Interviewers want to see that you recognize rotational/reflection symmetry and convert shapes into a normalized representation. Explaining the brute-force comparison first shows understanding of the equivalence rule, while the hashing approach demonstrates strong algorithm design and practical use of transformations and hash sets.

Solution

Code

Python

Java

C++

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Pairwise Shape ComparisonO(I² * K)O(I * K)Useful for understanding transformations and equivalence rules during initial reasoning
DFS + Canonical Shape HashingO(m * n * K)O(m * n)Optimal general solution for counting distinct islands under rotation and reflection

Video Solution

711. Number of Distinct Islands II (Leetcode Hard) • Programming Live with Larry • 2,356 views views

Watch 1 more video solutions →

Frequently Asked Questions

Is Number of Distinct Islands II easy or hard?
Number of Distinct Islands II is classified as a Hard problem on LeetCode. The difficulty comes from handling geometric transformations (rotations and reflections) and creating a canonical representation that allows efficient hashing.
Number of Distinct Islands II Python/Java solution
Most solutions use DFS to collect coordinates, generate all rotations and reflections, normalize the coordinates, and store the canonical representation in a hash set. The same logic translates cleanly to Python, Java, and C++ using lists/arrays and hash-based sets.
How to solve Number of Distinct Islands II in O(n)?
Treat the grid traversal as O(m*n). Use DFS to collect island coordinates relative to the starting cell. Generate the 8 rotational and reflection transformations, normalize them, and store the canonical representation in a hash set. This avoids pairwise comparisons between islands.
What is the best approach for Number of Distinct Islands II?
The best approach is DFS with canonical shape hashing. Traverse each island, collect relative coordinates, generate all 8 rotations/reflections, normalize them, and store the smallest representation in a hash set. This ensures islands that differ only by rotation or reflection map to the same canonical signature.
Is Number of Distinct Islands II asked at Google/Amazon/Meta?
Number of Distinct Islands II is a classic grid and hashing problem commonly associated with companies like Google and Meta. It tests graph traversal, shape normalization, and hashing techniques that frequently appear in advanced interview rounds.
What data structure is used in Number of Distinct Islands II?
The main data structures are a hash set to store canonical island signatures and recursion or a stack for DFS traversal. Arrays or lists store island coordinates, which are transformed and normalized before hashing.
What is the time complexity of Number of Distinct Islands II?
The optimal solution runs in O(m * n * K) time, where m and n are grid dimensions and K is the number of cells in an island. DFS visits each cell once, and each island requires generating and normalizing up to 8 transformations.

Ready to solve this problem?

Practice Number of Distinct Islands II with our built-in code editor and test cases.

Practice on FleetCode