← Back to Codes

2026-06-09 16:36:42

Number of Islands in Python and Java | LeetCode #200

Learn how to solve Number of Islands in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Number of Islands in Python and Java

In this tutorial, we will learn LeetCode #200: Number of Islands in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Number of Islands Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use depth first search because it gives a clean and optimized solution.

Example input:
grid = [["1","1","0"],["0","1","0"],["1","0","1"]]

Expected result:
Output: 3

Explanation:
There are three separated land groups.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
grid = [["1","1","0"],["0","1","0"],["1","0","1"]]

Approach:
depth first search

We update variables step by step until we reach:
Output: 3

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why depth first search is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this grid.

1 1 0
0 1 0
1 0 1

Start scanning from top-left.

Step 2
Cell (0, 0) is land.

So we found island number 1.

Now DFS marks connected land cells:
(0, 0), (0, 1), (1, 1)

Step 3
Continue scanning. Cell (2, 0) is land and not visited.

So we found island number 2.

Step 4
Cell (2, 2) is also land and not visited.

So we found island number 3.

Final answer = 3

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: 3

Example 1

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

Output:
Output: 3

Explanation:
There are three separated land groups.

Example 2

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

Output:
3

Explanation:
There are three separated islands.

Python Code

Here is the complete Python solution for LeetCode #200.

class IslandCounter:
    def num_islands(self, grid):
        if not grid:
            return 0

        rows = len(grid)
        cols = len(grid[0])
        count = 0

        def dfs(row, col):
            if row < 0 or col < 0 or row == rows or col == cols or grid[row][col] != "1":
                return
            grid[row][col] = "0"
            dfs(row + 1, col)
            dfs(row - 1, col)
            dfs(row, col + 1)
            dfs(row, col - 1)

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == "1":
                    count += 1
                    dfs(row, col)

        return count


counter = IslandCounter()
grid1 = [["1", "1", "0"], ["0", "1", "0"], ["1", "0", "1"]]
grid2 = [["1", "0"], ["0", "1"]]
print(counter.num_islands(grid1))  # Output: 3
print(counter.num_islands(grid2))  # Output: 2

Java Code

Here is the complete Java solution for LeetCode #200.

class IslandCounter {
    public int numIslands(char[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        int count = 0;

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (grid[row][col] == '1') {
                    count++;
                    dfs(grid, row, col);
                }
            }
        }

        return count;
    }

    private void dfs(char[][] grid, int row, int col) {
        if (row < 0 || col < 0 || row == grid.length || col == grid[0].length || grid[row][col] != '1') return;
        grid[row][col] = '0';
        dfs(grid, row + 1, col);
        dfs(grid, row - 1, col);
        dfs(grid, row, col + 1);
        dfs(grid, row, col - 1);
    }

    public static void main(String[] args) {
        IslandCounter counter = new IslandCounter();
        char[][] grid1 = {{'1','1','0'}, {'0','1','0'}, {'1','0','1'}};
        char[][] grid2 = {{'1','0'}, {'0','1'}};
        System.out.println(counter.numIslands(grid1)); // 3
        System.out.println(counter.numIslands(grid2)); // 2
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #200: Number of Islands becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.