Count islands using BFS without modifying grid
Company: TikTok
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: HR Screen
Quick Answer: This question evaluates understanding of BFS-based graph traversal on grids, managing visited state without modifying the input, and techniques for encoding island shapes to detect distinct configurations.
Count Islands using BFS (without modifying the grid)
Constraints
- 1 <= m, n <= 200
- grid[i][j] is 0 or 1
- Must use BFS
- Must NOT modify grid in-place; use a separate visited structure
Examples
Input: ([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]],)
Expected Output: 3
Explanation: Top-left 2x2 block (1 island), the single 1 at (2,2), and the horizontal pair at (3,3)-(3,4) = 3 islands.
Input: ([[1,1,1],[0,1,0],[1,1,1]],)
Expected Output: 1
Explanation: All land cells are connected through the center column into one island.
Hints
- Scan every cell. When you hit a land cell that hasn't been visited yet, you've found a new island — increment your count and BFS-flood the whole island.
- Because you can't overwrite the grid, keep a parallel boolean `visited[m][n]` matrix and mark cells there as you enqueue them.
- Mark a cell visited at enqueue time (not dequeue time) so the same cell is never added to the queue twice.
Count Distinct Island Shapes (translation-invariant)
Constraints
- 1 <= m, n <= 200
- grid[i][j] is 0 or 1
- Same shape = translation only (no rotation/reflection)
- Use BFS; do NOT modify grid in-place
Examples
Input: ([[1,1,0,0],[1,0,0,0],[0,0,1,1],[0,0,1,0]],)
Expected Output: 1
Explanation: Both islands are the same L-tromino shape after translation, so there is 1 distinct shape.
Input: ([[1,1,0,1,1],[0,0,0,0,0],[1,1,0,1,0],[1,0,0,1,0]],)
Expected Output: 3
Explanation: Two horizontal dominoes (same shape), one L-tromino, and one vertical domino -> distinct shapes are {horizontal domino, L-tromino, vertical domino} = 3.
Hints
- Collect every cell of an island during BFS, then convert that set of coordinates into a translation-invariant signature.
- To make the signature translation-invariant, subtract the island's minimum row and minimum column from every cell so each island is re-anchored to (0,0).
- Sort the normalized coordinate list and store it (as a tuple/string) in a set. The answer is the size of the set. Sorting guarantees two islands discovered in different orders produce identical keys.