Number of distinct islands

Asked atKotakOracle
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

You are given a 2D matrix grid of size N × M, where each cell contains either 0 or 1. Find the number of distinct islands where a group of connected 1s (horizontally or vertically) forms an island. Two islands are considered to be same if and only if one island is equal to another (not rotated or reflected).

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:

Same colored islands are equal. We have 2 equal islands, so we have only 1 distinct island.

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:

Same colored islands are equal. We have 4 islands, but 2 of them are equal, So we have 3 distinct islands..

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

  • 1 <= N, M <= 500
  • grid[i][j] == 0 or 1

cpp

class Solution
{
public:
    int countDistinctIslands(vector<vector<int>> &grid){
        
    }
};

java

class Solution {
    public int countDistinctIslands(int[][] grid) {
      
    }
}

python

class Solution:
    def countDistinctIslands(self, grid):

javascript

class Solution {
    countDistinctIslands(grid) {
       
    }
}

csharp

public class Solution
{
    public int CountDistinctIslands(List<List<int>> grid)
    {
      
    }
}

go

func countDistinctIslands(grid [][]int) int {

}
Stuck? Show a way to structure it+
  1. 01Scan the grid for unvisited land
  2. 02DFS each island while collecting relative coordinates
  3. 03Serialize the ordered relative shape consistently
  4. 04Insert the signature into a set

Reference answer

Then expect these follow-ups

  • How do you treat rotations as identical?

    Tests: follow-up reasoning

  • Can BFS be used instead of DFS?

    Tests: follow-up reasoning

Hiring now

Get the Kotak interview, not just the prep

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
Or practice this question first

Next question