Number of Islands — LeetCode 200 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindArrayMatrix
Problem
#200
Pattern
Union-Find
Reading time
3 min

The problem

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

Example

Input
grid = [
Output
1

Python solution

Python
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def dfs(i, j):
            grid[i][j] = '0'
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':
                    dfs(x, y)

        ans = 0
        dirs = (-1, 0, 1, 0, -1)
        m, n = len(grid), len(grid[0])
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    dfs(i, j)
                    ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 200. Number of Islands is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 200. Number of Islands?
LeetCode 200. Number of Islands is rated Medium on LeetCode.
What is the time complexity of LeetCode 200. Number of Islands?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 200. Number of Islands?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 200. Number of Islands cover?
LeetCode 200. Number of Islands is tagged Depth-First Search, Breadth-First Search, Union Find, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview