← Pinterest Interview Insights
Classic BFS/DFS problem and I knew it immediately, which almost made it worse because I rushed into code without talking through edge cases first.
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 adjacent land cells and count distinct sets.
Pro tip: Discuss trade-offs between BFS and DFS, especially regarding recursion depth and memory usage, and mention how to handle very large grids by using iterative BFS to avoid stack overflow.
Confirm the definition of an island, adjacency rules (horizontal/vertical), and grid boundaries. Ask about input size and constraints to choose the right algorithm.
Decide between BFS, DFS, or Union-Find based on constraints and personal comfort. Explain why you chose it, considering time and space complexity.
Describe how you will iterate through each cell, and when you find a '1', increment the count and traverse all connected '1's, marking them as visited (e.g., set to '0' or use a visited matrix).
State that time complexity is O(M*N) where M and N are grid dimensions, as each cell is visited once. Space complexity is O(M*N) in the worst case for the queue/stack or recursion depth.
Walk through a small example to verify correctness, including edge cases like empty grid, all water, all land, and single row/column.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.