Coding Medium Software Engineer Backend Full Stack

Given a 2D grid of '1's (land) and '0's (water), count the number of islands (Number of Islands).

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Optimal Breadth-First Search (BFS) / Depth-First Search (DFS) Approach:
- Iterate through the grid; when unvisited land ('1') is found, increment island count and sink the connected land mass using DFS/BFS.

def num_islands(grid: list[list[str]]) -> int:
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    count = 0
    def dfs(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1':
            return
        grid[r][c] = '0'  # Mark visited by sinking
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                count += 1
                dfs(r, c)
    return count

Complexity & Key Logic:
- Time Complexity: O(M * N) where M is rows and N is columns; each cell visited a constant number of times.
- Space Complexity: O(M * N) worst-case recursion stack if entire grid is filled with land.
- Algorithm Details:
- Mutate grid in-place (grid[r][c] = '0') to eliminate extra visited set memory.
- Explore 4-directionally (up, down, left, right) until boundary or water reached.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Coding Questions