I know this problem cold with BFS but they wanted Union-Find, which I use way less often.
Use a graph traversal algorithm like BFS or DFS to explore each unvisited land cell and mark all connected land cells as visited, incrementing the island count for each new traversal. Alternatively, use Union-Find to group connected land cells and count distinct sets.
Pro tip: Discuss trade-offs between BFS, DFS, and Union-Find in terms of time/space complexity and practical considerations like recursion depth limits and input mutation. Mention that modifying the grid in-place can save space but may not be allowed; clarify with the interviewer.
Ask about grid size limits, whether the grid can be modified, and if diagonal connections count. Confirm that islands are only horizontally/vertically connected.
Select BFS, DFS, or Union-Find based on constraints and your comfort. Explain why you chose it, considering time/space complexity and potential stack overflow with DFS.
Describe iterating through each cell; when encountering unvisited land, increment island count and traverse all connected land cells, marking them visited.
State time complexity O(m*n) and space complexity O(m*n) in worst case. Discuss edge cases: empty grid, all water, all land, single row/column.
Mention in-place modification to save space, using iterative BFS to avoid recursion limits, and Union-Find with path compression and union by rank.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.