Compute island size in grid
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Compute island size in grid states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Compute Island Size in Grid
Constraints
- 1 <= m, n (grid may also be empty: [] or [[]])
- grid[i][j] is 0 or 1
- r and c may be any integer (out-of-bounds returns 0)
- Islands are connected 4-directionally only (no diagonals)
Examples
Input: ([[1,1,0],[0,1,0],[0,0,1]], 0, 0)
Expected Output: 3
Explanation: Cells (0,0),(0,1),(1,1) form one connected island of size 3.
Input: ([[1,1,0],[0,1,0],[0,0,1]], 2, 2)
Expected Output: 1
Explanation: Cell (2,2) is an isolated land cell; its island has size 1.
Hints
- The base cases are the tricky part: handle empty grid, out-of-bounds (r, c), and water at the start before doing any traversal.
- Use an explicit stack (iterative DFS) or a queue (BFS) to flood-fill. Mark a cell visited the moment you push it, not when you pop it, to avoid double-counting.
- An auxiliary visited set keeps the input grid immutable; alternatively you could temporarily flip 1s to 0s, but state the trade-off.
Largest Island in the Grid (Follow-up)
Constraints
- 1 <= m, n (grid may also be empty: [] or [[]])
- grid[i][j] is 0 or 1
- Islands are connected 4-directionally only (no diagonals)
- Return 0 when the grid contains no land
Examples
Input: ([[1,1,0],[0,1,0],[0,0,1]],)
Expected Output: 3
Explanation: Largest island is the size-3 cluster at the top-left; the lone (2,2) cell has size 1.
Input: ([[0,0],[0,0]],)
Expected Output: 0
Explanation: No land in the grid, so the largest island size is 0.
Hints
- Reuse the single-island flood-fill, but call it from a double loop over every cell, skipping cells you have already visited.
- A shared visited matrix across the whole scan guarantees O(m*n) total work — you never re-traverse a counted island.
- Track the running maximum island size; the answer is 0 if every cell is water.