Number of islands

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

The problem

Given a grid of size N x M (N is the number of rows and M is the number of columns in the grid) consisting of '0's (Water) and ‘1's(Land). Find the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.

Input: grid = [ ["1", "1", "1", "0", "1"], ["1", "0", "0", "0", "0"], ["1", "1", "1", "0", "1"], ["0", "0", "0", "1", "1"] ] Output: 2 Explanation: This grid contains 2 islands. Each '1' represents a piece of land, and the islands are formed by connecting adjacent lands horizontally or vertically. Despite some islands having a common edge, they are considered separate islands because there is no land connectivity in any of the eight directions between them. Therefore, the grid contains 2 islands.

Input: grid = [ ["1", "0", "0", "0", "1"], ["0", "1", "0", "1", "0"], ["0", "0", "1", "0", "0"], ["0", "1", "0", "1"," 0"] ] Output: 1 Explanation: In the given grid, there's only one island as all the '1's are connected either horizontally, vertically, or diagonally, forming a single contiguous landmass surrounded by water on all sides.

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

· N == grid.length · M == grid[i].length · 1 <= N, M <= 300 · grid[i][j] is '0' or '1'.

cpp

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

java

class Solution {
    public int numIslands(char[][] grid) {
       
    }
}

python

class Solution:
    def numIslands(self, grid):

javascript

class Solution {
    numIslands(grid) {
     
    }
}

csharp

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

go

func NumIslands(grid [][]byte) int {
	
}
Stuck? Show a way to structure it+
  1. 01Scan every grid cell and start a traversal whenever an unvisited land cell is found.
  2. 02Mark the entire connected component using the eight direction offsets required by this version.
  3. 03Increment the island count once per traversal, not once per land cell.
  4. 04Explain how in-place marking or a visited matrix prevents repeated work.

Reference answer

Then expect these follow-ups

  • How would the result differ if only four directions were allowed?

    Tests: requirements awareness

  • How would you process a grid too large to fit in memory?

    Tests: scalability reasoning

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question