Classic problem and I knew it, but I still fumbled around for a minute deciding between BFS and DFS before just going with DFS because it felt cleaner to write recursively.
Use a graph traversal algorithm like DFS or BFS to explore each unvisited land cell and mark all connected land cells as visited, incrementing the island count for each traversal. Alternatively, use Union-Find to group connected land cells and count distinct sets. Clearly explain the chosen approach, its complexity, and handle edge cases.
Pro tip: At Amazon, emphasize scalability and efficiency: discuss how your solution handles large grids and why you chose a particular traversal order. Mention that you can optimize space by modifying the grid in-place if allowed, but clarify the trade-off.
Confirm the definition of an island, connectivity (4-directional), and input constraints. Ask about grid size, mutability, and edge cases like empty grid.
Select between DFS, BFS, or Union-Find based on trade-offs. Explain why your choice is suitable for the given constraints.
Describe the steps: iterate through each cell, when encountering unvisited land, increment count and traverse all connected land cells, marking them visited.
State time and space complexity. For DFS/BFS: O(M*N) time and O(M*N) space in worst case (e.g., all land). For Union-Find: O(M*N α(M*N)) time and O(M*N) space.
Discuss edge cases: empty grid, all water, all land, single row/column. Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.