KatInterview

200. Number of 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 separate "islands" in a 2D grid. An island is defined as a group of '1's (land) that are connected horizontally or vertically. All other cells are '0's (water). This is a classic graph problem about finding the number of connected components.

Solution

Number of Islands in Python

class Solution:
    def numIslands(self, grid: list[list[str]]) -> int:
        # Handle empty grid case, though constraints say it won't be empty.
        if not grid or not grid[0]:
            return 0

        rows, cols = len(grid), len(grid[0])
        island_count = 0

        def dfs(r, c):
            # Base cases for stopping recursion: out of bounds or water/visited cell.
            if not (0 <= r < rows and 0 <= c < cols and grid[r][c] == '1'):
                return
            
            # Mark the current cell as visited by changing its value.
            grid[r][c] = '0'
            
            # Explore neighbors in 4 directions recursively.
            dfs(r + 1, c) # Down
            dfs(r - 1, c) # Up
            dfs(r, c + 1) # Right
            dfs(r, c - 1) # Left

        # Iterate through each cell in the grid.
        for r in range(rows):
            for c in range(cols):
                # If a '1' is found, it's a new island.
                if grid[r][c] == '1':
                    island_count += 1
                    # Start DFS to find all parts of the island.
                    dfs(r, c)
        
        return island_count

Number of Islands in Java

class Solution {
    public int numIslands(char[][] grid) {
        // Handle empty grid case, though constraints say it won't be empty.
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int rows = grid.length;
        int cols = grid[0].length;
        int islandCount = 0;

        // Iterate through each cell of the grid.
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // If a cell contains '1', it's a new island.
                if (grid[i][j] == '1') {
                    islandCount++;
                    // Start DFS to find all connected land and sink it.
                    dfs(grid, i, j);
                }
            }
        }

        return islandCount;
    }

    private void dfs(char[][] grid, int r, int c) {
        int rows = grid.length;
        int cols = grid[0].length;

        // Check for boundary conditions and if the cell is water or visited.
        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') {
            return;
        }

        // Mark the current cell as visited by 'sinking' it.
        grid[r][c] = '0';

        // Explore neighbors in 4 directions.
        dfs(grid, r + 1, c); // Down
        dfs(grid, r - 1, c); // Up
        dfs(grid, r, c + 1); // Right
        dfs(grid, r, c - 1); // Left
    }
}

Number of Islands in C++

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        // Handle empty grid case, though constraints say it won't be empty.
        if (grid.empty() || grid[0].empty()) {
            return 0;
        }

        int rows = grid.size();
        int cols = grid[0].size();
        int islandCount = 0;

        // Iterate through each cell of the grid.
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                // If we find a '1', it's the start of a new island.
                if (grid[i][j] == '1') {
                    islandCount++;
                    // Use DFS to find all parts of this island and sink them (change '1' to '0').
                    dfs(grid, i, j);
                }
            }
        }

        return islandCount;
    }

private:
    void dfs(vector<vector<char>>& grid, int r, int c) {
        int rows = grid.size();
        int cols = grid[0].size();

        // Base cases for recursion termination:
        // 1. Out of bounds (row or column).
        // 2. The cell is water ('0') or already visited (also '0').
        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') {
            return;
        }

        // Mark the current land cell as visited by changing it to '0'.
        grid[r][c] = '0';

        // Recursively explore all 4 adjacent cells.
        dfs(grid, r + 1, c); // Down
        dfs(grid, r - 1, c); // Up
        dfs(grid, r, c + 1); // Right
        dfs(grid, r, c - 1); // Left
    }
};

Number of Islands in TypeScript

function numIslands(grid: string[][]): number {
    // Handle empty grid case, though constraints say it won't be empty.
    if (!grid || grid.length === 0) {
        return 0;
    }

    const rows = grid.length;
    const cols = grid[0].length;
    let islandCount = 0;

    // DFS helper function
    function dfs(r: number, c: number) {
        // Base cases for stopping recursion: out of bounds or water/visited cell.
        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === '0') {
            return;
        }

        // Mark the current land cell as visited by 'sinking' it.
        grid[r][c] = '0';

        // Explore neighbors in 4 directions recursively.
        dfs(r + 1, c); // Down
        dfs(r - 1, c); // Up
        dfs(r, c + 1); // Right
        dfs(r, c - 1); // Left
    }

    // Iterate through each cell of the grid.
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            // If we find a '1', it's the start of a new island.
            if (grid[i][j] === '1') {
                islandCount++;
                // Use DFS to find all parts of this island and sink them.
                dfs(i, j);
            }
        }
    }

    return islandCount;
};

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.