711. Number of Distinct Islands II
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to count the number of distinct islands in a binary grid. An island is a 4-directionally connected group of 1s. The crucial part is the definition of "distinct". Two islands are considered the same if one can be transformed into the other through rotation (90, 180, 270 degrees) or reflection (horizontal or vertical). This means we need to find a way to represent each island's shape that is invariant under these transformations. This is a classic problem of finding a "canonical representation" for an object under a group of transformations.
Solution
Number of Distinct Islands II in Python
import collections
class Solution:
def numDistinctIslands2(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
visited = set()
distinct_shapes = set()
for r in range(m):
for c in range(n):
if grid[r][c] == 1 and (r, c) not in visited:
# Use BFS to find all parts of the island
shape = []
q = collections.deque([(r, c)])
visited.add((r, c))
while q:
row, col = q.popleft()
shape.append((row, col))
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = row + dr, col + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1 and (nr, nc) not in visited:
visited.add((nr, nc))
q.append((nr, nc))
# Find the canonical representation of the shape
canonical_form = self._get_canonical(shape)
distinct_shapes.add(canonical_form)
return len(distinct_shapes)
def _get_canonical(self, shape: list[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
# Generate 8 transformations (symmetries of a square)
forms = [] # This will hold 8 transformed versions of the shape
# Each version is a list of points (tuples)
transformed_shapes = [[] for _ in range(8)]
for r, c in shape:
transformed_shapes[0].append((r, c))
transformed_shapes[1].append((r, -c))
transformed_shapes[2].append((-r, c))
transformed_shapes[3].append((-r, -c))
transformed_shapes[4].append((c, r))
transformed_shapes[5].append((c, -r))
transformed_shapes[6].append((-c, r))
transformed_shapes[7].append((-c, -r))
for form in transformed_shapes:
# Normalize the shape by translating it to the origin
min_r = min(p[0] for p in form)
min_c = min(p[1] for p in form)
normalized = sorted([(p[0] - min_r, p[1] - min_c) for p in form])
forms.append(tuple(normalized))
# The canonical form is the lexicographically smallest of all transformations
return min(forms)
Number of Distinct Islands II in Java
class Solution {
private int m, n;
private int[][] grid;
private boolean[][] visited;
public int numDistinctIslands2(int[][] grid) {
this.grid = grid;
this.m = grid.length;
this.n = grid[0].length;
this.visited = new boolean[m][n];
Set<String> distinctShapes = new HashSet<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (grid[r][c] == 1 && !visited[r][c]) {
List<int[]> shape = new ArrayList<>();
dfs(r, c, shape);
distinctShapes.add(getCanonical(shape));
}
}
}
return distinctShapes.size();
}
private void dfs(int r, int c, List<int[]> shape) {
if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c] || grid[r][c] == 0) {
return;
}
visited[r][c] = true;
shape.add(new int[]{r, c});
dfs(r + 1, c, shape);
dfs(r - 1, c, shape);
dfs(r, c + 1, shape);
dfs(r, c - 1, shape);
}
private String getCanonical(List<int[]> shape) {
// Generate 8 transformations (symmetries of a square)
List<List<int[]>> forms = new ArrayList<>();
for (int i = 0; i < 8; i++) {
forms.add(new ArrayList<>());
}
for (int[] p : shape) {
int r = p[0], c = p[1];
forms.get(0).add(new int[]{r, c});
forms.get(1).add(new int[]{r, -c});
forms.get(2).add(new int[]{-r, c});
forms.get(3).add(new int[]{-r, -c});
forms.get(4).add(new int[]{c, r});
forms.get(5).add(new int[]{c, -r});
forms.get(6).add(new int[]{-c, r});
forms.get(7).add(new int[]{-c, -r});
}
List<String> normalizedForms = new ArrayList<>();
for (List<int[]> form : forms) {
// Normalize the shape by translating it to the origin
int minR = Integer.MAX_VALUE, minC = Integer.MAX_VALUE;
for (int[] p : form) {
minR = Math.min(minR, p[0]);
minC = Math.min(minC, p[1]);
}
List<int[]> normalized = new ArrayList<>();
for (int[] p : form) {
normalized.add(new int[]{p[0] - minR, p[1] - minC});
}
// Sort the points to have a consistent representation
normalized.sort((a, b) -> {
if (a[0] != b[0]) return a[0] - b[0];
return a[1] - b[1];
});
// Serialize the sorted points into a string for hashing
StringBuilder sb = new StringBuilder();
for (int[] p : normalized) {
sb.append(p[0]).append(",").append(p[1]).append(";");
}
normalizedForms.add(sb.toString());
}
// Sort all 8 representations and pick the lexicographically smallest one
Collections.sort(normalizedForms);
return normalizedForms.get(0);
}
}
Number of Distinct Islands II in C++
class Solution {
public:
int numDistinctIslands2(vector<vector<int>>& grid) {
m = grid.size();
n = grid[0].size();
this->grid = &grid;
visited.assign(m, vector<bool>(n, false));
set<string> distinctShapes;
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
if ((*this->grid)[r][c] == 1 && !visited[r][c]) {
vector<pair<int, int>> shape;
dfs(r, c, shape);
distinctShapes.insert(getCanonical(shape));
}
}
}
return distinctShapes.size();
}
private:
int m, n;
vector<vector<int>>* grid;
vector<vector<bool>> visited;
void dfs(int r, int c, vector<pair<int, int>>& shape) {
if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c] || (*grid)[r][c] == 0) {
return;
}
visited[r][c] = true;
shape.push_back({r, c});
int dr[] = {0, 0, 1, -1};
int dc[] = {1, -1, 0, 0};
for (int i = 0; i < 4; ++i) {
dfs(r + dr[i], c + dc[i], shape);
}
}
string getCanonical(vector<pair<int, int>>& shape) {
// Generate 8 transformations (symmetries of a square)
vector<vector<pair<int, int>>> forms(8);
for (auto& p : shape) {
int r = p.first, c = p.second;
forms[0].push_back({r, c});
forms[1].push_back({r, -c});
forms[2].push_back({-r, c});
forms[3].push_back({-r, -c});
forms[4].push_back({c, r});
forms[5].push_back({c, -r});
forms[6].push_back({-c, r});
forms[7].push_back({-c, -r});
}
vector<string> normalizedForms;
for (auto& form : forms) {
// Normalize the shape by translating it to the origin
int minR = INT_MAX, minC = INT_MAX;
for (auto& p : form) {
minR = min(minR, p.first);
minC = min(minC, p.second);
}
vector<pair<int, int>> normalized;
for (auto& p : form) {
normalized.push_back({p.first - minR, p.second - minC});
}
// Sort the points to have a consistent representation
sort(normalized.begin(), normalized.end());
// Serialize the sorted points into a string for hashing
string s = "";
for (auto& p : normalized) {
s += to_string(p.first) + "," + to_string(p.second) + ";";
}
normalizedForms.push_back(s);
}
// Sort all 8 representations and pick the lexicographically smallest one
sort(normalizedForms.begin(), normalizedForms.end());
return normalizedForms[0];
}
};
Number of Distinct Islands II in TypeScript
function numDistinctIslands2(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
const visited: boolean[][] = Array(m).fill(0).map(() => Array(n).fill(false));
const distinctShapes = new Set<string>();
const getCanonical = (shape: [number, number][]): string => {
// Generate 8 transformations (symmetries of a square)
const forms: [number, number][][] = Array(8).fill(0).map(() => []);
for (const [r, c] of shape) {
forms[0].push([r, c]);
forms[1].push([r, -c]);
forms[2].push([-r, c]);
forms[3].push([-r, -c]);
forms[4].push([c, r]);
forms[5].push([c, -r]);
forms[6].push([-c, r]);
forms[7].push([-c, -r]);
}
const normalizedForms: string[] = [];
for (const form of forms) {
// Normalize the shape by translating it to the origin
let minR = Infinity, minC = Infinity;
for (const [r, c] of form) {
minR = Math.min(minR, r);
minC = Math.min(minC, c);
}
const normalized: [number, number][] = form.map(([r, c]) => [r - minR, c - minC]);
// Sort the points to have a consistent representation
normalized.sort((a, b) => {
if (a[0] !== b[0]) return a[0] - b[0];
return a[1] - b[1];
});
// Serialize the sorted points into a string for hashing
let sb = "";
for (const p of normalized) {
sb += p[0] + "," + p[1] + ";";
}
normalizedForms.push(sb);
}
// Sort all 8 representations and pick the lexicographically smallest one
normalizedForms.sort();
return normalizedForms[0];
};
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] === 1 && !visited[r][c]) {
const shape: [number, number][] = [];
const q: [number, number][] = [[r, c]];
visited[r][c] = true;
// BFS to find all parts of the island
let head = 0;
while(head < q.length){
const [row, col] = q[head++];
shape.push([row, col]);
const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];
for (const [dr, dc] of dirs) {
const nr = row + dr;
const nc = col + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] === 1 && !visited[nr][nc]) {
visited[nr][nc] = true;
q.push([nr, nc]);
}
}
}
distinctShapes.add(getCanonical(shape));
}
}
}
return distinctShapes.size;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.