I went straight to BFS which felt right, but spent too long second-guessing whether to use DFS instead.
Treat the grid as a graph and use DFS or BFS to explore each unvisited land cell, marking all connected land cells as visited. Count the number of times you initiate a traversal from an unvisited land cell. Alternatively, use Union-Find to merge adjacent land cells and count distinct sets.
Pro tip: Clarify edge cases upfront (empty grid, all water, all land) and mention that you can mutate the grid to save space, but ask if that's acceptable. Also, discuss time and space complexity trade-offs between DFS/BFS and Union-Find.
Confirm the definition of an island, adjacency rules (4-directional), and input constraints (grid size, mutability). Ask about edge cases like empty grid or no land.
Decide between DFS/BFS (simpler, O(mn) time, O(mn) space worst-case) and Union-Find (good for dynamic connectivity, O(mn α) time). Explain your choice based on constraints.
Iterate through each cell; when you find an unvisited '1', increment island count and launch a traversal (DFS/BFS) to mark all connected '1's as visited (e.g., set to '0' or use a visited set).
State time complexity O(mn) since each cell is visited once, and space complexity O(mn) for recursion stack or queue in worst case (all land). Mention that Union-Find uses O(mn) space for parent array.
Walk through a small example (e.g., 3x3 with one island) and edge cases (empty grid, single row/column, all water, all land) to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.