Taro Logo

Number of Islands

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+75
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
6.3K views
Topics:
GraphsArrays

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. You may assume all four edges of the grid are all surrounded by water.

Example 1:

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

Example 2:

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

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the grid be empty or null, and if so, should we return 0 in that case?
  2. Are the dimensions of the grid guaranteed to be fixed (i.e., a well-formed 2D matrix), or can the rows be of varying lengths?
  3. Is it possible to modify the input grid during the traversal (e.g., to mark visited cells and save space), or is the input expected to remain immutable?
  4. Can an island wrap around the edges of the grid (i.e., treating the grid as a torus), or are connections strictly bounded by the grid dimensions?
  5. What character values other than '1' and '0' could potentially appear in the grid, or should we assume strictly valid binary input?

Brute Force Solution

Approach

Imagine looking at a vast map filled with land and water, and your goal is to count every separate patch of land. The brute force approach involves inspecting every single location on the map, and whenever you find a piece of land, you exhaustively explore every possible path connected to it to map out its entire shape.

Here's how the algorithm would work step-by-step:

  1. Scan the entire map from top to bottom, left to right, searching for any piece of land.
  2. When you find a piece of land that you have not explored yet, count it as a new island.
  3. To make sure you do not count the same island twice, try to follow every possible path outward from that land in all directions.
  4. Continue following every connected piece of land until you reach water or the edge of the map, essentially walking every possible route within that specific landmass.
  5. Mark every part of that landmass as visited so you know you have fully explored it.
  6. Resume scanning the rest of the map for any other unvisited pieces of land.
  7. Repeat this entire process of searching and exploring until every single location on the entire map has been checked.

Code Implementation

def numIslands(grid):
    if not grid:
        return 0

    row_count = len(grid)
    col_count = len(grid[0])
    island_counter = 0

    # Scan the entire map to find unvisited land starting points for new islands
    for current_row in range(row_count):
        for current_col in range(col_count):
            if grid[current_row][current_col] == "1":
                island_counter += 1
                
                # Exhaustively explore and sink all connected land to prevent duplicate counting
                stack = [(current_row, current_col)]
                while stack:
                    row_pos, col_pos = stack.pop()
                    
                    if 0 <= row_pos < row_count and 0 <= col_pos < col_count and grid[row_pos][col_pos] == "1":
                        grid[row_pos][col_pos] = "0"
                        stack.append((row_pos + 1, col_pos))
                        stack.append((row_pos - 1, col_pos))
                        stack.append((row_pos, col_pos + 1))
                        stack.append((row_pos, col_pos - 1))

    return island_counter

Big(O) Analysis

Time Complexity
O(M * N) – Scanning the entire map requires nested loops that iterate through all M rows and N columns to inspect every single location. When an unvisited piece of land is found, the traversal explores up to all M * N connected cells to mark them as visited, ensuring each cell is processed a constant number of times. Summing these operations across the entire grid results in proportional work to the total number of cells. This overall process approximates M * N operations, which simplifies to O(M * N) where M and N are the dimensions of the grid.
Space Complexity
O(M * N) – The space complexity is driven by the recursion stack used during depth-first exploration and the mechanism for marking visited locations. In the worst-case scenario where the entire grid is a single massive island, the recursive calls will traverse every single cell, leading to a maximum recursion depth proportional to the total number of cells in the grid. If we define N as the total number of cells on the map, this deepest possible traversal requires auxiliary stack memory that scales linearly with N. Therefore, the overall extra memory simplifies to Big O notation of O(N), or O(R * C) where R and C are the grid dimensions.

Optimal Solution

Approach

Imagine scanning a vast map of land and water from above to count every separate landmass. The best way to solve this is to systematically search the map, and whenever you spot a piece of land, you instantly explore and mark its entire connected region so you never count it twice.

Here's how the algorithm would work step-by-step:

  1. Scan across the entire map from top to bottom, left to right, looking for an unmarked piece of land.
  2. Whenever you discover a fresh piece of land, click a mental counter upward because you have just found a new island.
  3. From that specific piece of land, immediately look in all four directions to find any neighboring land touching it.
  4. Travel outward to those neighboring pieces of land and mark them as visited so nobody mistakes them for a separate island.
  5. Keep spreading outward like a ripple in water until you have touched every single piece of land connected to the original discovery.
  6. Once the entire connected island is fully explored and marked off, return to scanning the rest of the map for the next unmarked land.
  7. Repeat this process until you have scanned the entire map, leaving you with the final count of all separate islands.

Code Implementation

class Solution:
    def numIslands(self, grid: list[list[str]]) -> int:
        if not grid:
            return 0

        row_count = len(grid)
        col_count = len(grid[0])
        island_counter = 0

        # We iterate through every cell to ensure no isolated landmass is ever missed.
        for current_row in range(row_count):
            for current_col in range(col_count):
                if grid[current_row][current_col] == '1':
                    island_counter += 1
                    queue_for_bfs = [(current_row, current_col)]
                    grid[current_row][current_col] = '0'

                    # We expand outward to consume all connected land so it forms a single counted island.
                    while queue_for_bfs:
                        active_row, active_col = queue_for_bfs.pop(0)
                        row_offsets = [-1, 1, 0, 0]
                        col_offsets = [0, 0, -1, 1]

                        for direction_index in range(4):
                            neighbor_row = active_row + row_offsets[direction_index]
                            neighbor_col = active_col + col_offsets[direction_index]

                            # We validate boundaries to prevent out-of-range errors during spread.
                            if 0 <= neighbor_row < row_count and 0 <= neighbor_col < col_count:
                                if grid[neighbor_row][neighbor_col] == '1':
                                    grid[neighbor_row][neighbor_col] = '0'
                                    queue_for_bfs.append((neighbor_row, neighbor_col))

        return island_counter

Big(O) Analysis

Time Complexity
O(M * N) – Scanning the map requires a nested loop that visits every single cell in the grid, where M is the number of rows and N is the number of columns. When an unvisited land cell is found, the exploration step triggers a recursive traversal that visits each connected land cell at most once. Because every cell in the grid is processed a constant number of times either during the initial scan or during the localized island exploration, the total operations scale linearly with the total number of cells. This means the overall workload approximates M * N operations, which simplifies to the Big O time complexity of O(M * N).
Space Complexity
O(M * N) – The auxiliary space is driven by the recursion stack used during the depth-first search to explore connected landmasses. In the worst-case scenario where the entire grid is filled with land, the recursion stack will grow to a maximum depth proportional to the total number of cells in the grid, which we denote as M times N. Since no additional data structures are used, this call stack determines the peak memory usage, resulting in a linear space complexity relative to the total size of the map.

Edge Cases

Empty grid or null input
How to Handle:
Check for null or empty grid at the start and return zero immediately.
Grid with dimensions 1x1 containing either '0' or '1'
How to Handle:
The traversal loop correctly processes the single cell and increments the count if it equals '1'.
Grid consisting entirely of '0's with no land
How to Handle:
The algorithm scans the entire grid without triggering any DFS or BFS expansions, returning a count of zero.
Grid consisting entirely of '1's forming one massive island
How to Handle:
The first '1' encountered triggers a full traversal of every cell in the grid, marking all as visited and returning a count of one.
Extremely large grid exceeding standard recursion depth limits
How to Handle:
Using an iterative Breadth-First Search or explicit stack Depth-First Search prevents stack overflow errors on massive inputs.
Snake-like or highly winding island shapes
How to Handle:
Graph traversal correctly visits all orthogonally connected neighbors regardless of the tortuous path of the land cells.
Ragged or non-rectangular grid dimensions
How to Handle:
Assuming a rectangular grid matrix, boundary checks ensure out-of-bounds errors are avoided when inspecting neighbors.
Mutating the input grid versus using a separate visited matrix
How to Handle:
The solution sinks visited land cells by mutating '1' to '0', avoiding extra space allocation for a visited set.
0/75 completed