KatInterview

694. Number of Distinct Islands

MediumSolutions in Python, Java, C++, TypeScript

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. Two islands are considered the same if one can be translated to overlap the other perfectly. Rotations and reflections are not allowed. The core of the problem is to devise a canonical representation for the shape of an island, one that is invariant to its position (translation) in the grid.

Solution

Number of Distinct Islands in Python

class Solution:
    def numDistinctIslands(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0
        
        m, n = len(grid), len(grid[0])
        distinct_islands = set()

        def dfs(r, c, island_shape):
            if not (0 <= r < m and 0 <= c < n and grid[r][c] == 1):
                return
            
            # Mark the cell as visited
            grid[r][c] = 0
            island_shape.append((r, c))

            # Explore 4-directionally
            dfs(r + 1, c, island_shape)
            dfs(r - 1, c, island_shape)
            dfs(r, c + 1, island_shape)
            dfs(r, c - 1, island_shape)

        for r in range(m):
            for c in range(n):
                if grid[r][c] == 1:
                    current_island_shape = []
                    dfs(r, c, current_island_shape)
                    
                    # Normalize the island shape
                    if not current_island_shape:
                        continue
                    
                    # Sort to get a consistent reference point (top-left)
                    current_island_shape.sort()
                    
                    r0, c0 = current_island_shape[0]
                    
                    # Create a canonical representation string
                    relative_shape = []
                    for r_cell, c_cell in current_island_shape:
                        relative_shape.append((r_cell - r0, c_cell - c0))
                    
                    distinct_islands.add(tuple(relative_shape))

        return len(distinct_islands)

Number of Distinct Islands in Java

class Solution {
    public int numDistinctIslands(int[][] grid) {
        int m = grid.length;
        if (m == 0) return 0;
        int n = grid[0].length;
        Set<String> distinctIslands = new HashSet<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    List<int[]> islandShape = new ArrayList<>();
                    dfs(grid, i, j, islandShape);
                    distinctIslands.add(normalize(islandShape));
                }
            }
        }

        return distinctIslands.size();
    }

    private void dfs(int[][] grid, int r, int c, List<int[]> islandShape) {
        int m = grid.length;
        int n = grid[0].length;

        if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) {
            return;
        }

        // Mark the cell as visited by changing it to 0
        grid[r][c] = 0;
        islandShape.add(new int[]{r, c});

        // Explore 4-directionally
        dfs(grid, r + 1, c, islandShape);
        dfs(grid, r - 1, c, islandShape);
        dfs(grid, r, c + 1, islandShape);
        dfs(grid, r, c - 1, islandShape);
    }

    private String normalize(List<int[]> islandShape) {
        // Sort the coordinates to get a consistent starting point (top-left)
        islandShape.sort((a, b) -> {
            if (a[0] != b[0]) {
                return a[0] - b[0];
            } else {
                return a[1] - b[1];
            }
        });

        StringBuilder canonicalShape = new StringBuilder();
        if (islandShape.isEmpty()) {
            return "";
        }

        int r0 = islandShape.get(0)[0];
        int c0 = islandShape.get(0)[1];

        for (int[] p : islandShape) {
            // Append relative coordinates to the string builder
            canonicalShape.append(p[0] - r0).append(",").append(p[1] - c0).append(";");
        }

        return canonicalShape.toString();
    }
}

Number of Distinct Islands in C++

class Solution {
public:
    int numDistinctIslands(vector<vector<int>>& grid) {
        int m = grid.size();
        if (m == 0) return 0;
        int n = grid[0].size();
        set<string> distinctIslands;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    vector<pair<int, int>> islandShape;
                    dfs(grid, i, j, islandShape);
                    distinctIslands.insert(normalize(islandShape));
                }
            }
        }

        return distinctIslands.size();
    }

private:
    void dfs(vector<vector<int>>& grid, int r, int c, vector<pair<int, int>>& islandShape) {
        int m = grid.size();
        int n = grid[0].size();

        if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) {
            return;
        }

        // Mark the cell as visited by changing it to 0
        grid[r][c] = 0;
        islandShape.push_back({r, c});

        // Explore 4-directionally
        dfs(grid, r + 1, c, islandShape);
        dfs(grid, r - 1, c, islandShape);
        dfs(grid, r, c + 1, islandShape);
        dfs(grid, r, c - 1, islandShape);
    }

    string normalize(vector<pair<int, int>>& islandShape) {
        // Sort the coordinates to get a consistent starting point (top-left)
        sort(islandShape.begin(), islandShape.end());

        string canonicalShape = "";
        if (islandShape.empty()) {
            return canonicalShape;
        }

        int r0 = islandShape[0].first;
        int c0 = islandShape[0].second;

        for (const auto& p : islandShape) {
            // Append relative coordinates to the string
            canonicalShape += to_string(p.first - r0) + "," + to_string(p.second - c0) + ";";
        }

        return canonicalShape;
    }
};

Number of Distinct Islands in TypeScript

function numDistinctIslands(grid: number[][]): number {
    const m = grid.length;
    if (m === 0) return 0;
    const n = grid[0].length;
    const distinctIslands: Set<string> = new Set();

    const dfs = (r: number, c: number, islandShape: number[][]) => {
        if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] === 0) {
            return;
        }

        // Mark the cell as visited
        grid[r][c] = 0;
        islandShape.push([r, c]);

        // Explore 4-directionally
        dfs(r + 1, c, islandShape);
        dfs(r - 1, c, islandShape);
        dfs(r, c + 1, islandShape);
        dfs(r, c - 1, islandShape);
    };

    const normalize = (islandShape: number[][]): string => {
        if (islandShape.length === 0) {
            return "";
        }

        // Sort coordinates to get a consistent starting point (top-left)
        islandShape.sort((a, b) => {
            if (a[0] !== b[0]) {
                return a[0] - b[0];
            } else {
                return a[1] - b[1];
            }
        });

        const r0 = islandShape[0][0];
        const c0 = islandShape[0][1];

        let canonicalShape = "";
        for (const p of islandShape) {
            canonicalShape += `${p[0] - r0},${p[1] - c0};`;
        }
        return canonicalShape;
    };

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === 1) {
                const islandShape: number[][] = [];
                dfs(i, j, islandShape);
                distinctIslands.add(normalize(islandShape));
            }
        }
    }

    return distinctIslands.size;
}

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.