Number of Islands
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Examples:** ```typescript numIslands([ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]) // 1 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(m * n)
- Space complexity: O(m * n)
Every cell in the m x n grid is visited a constant number of times.
Follow-Up Questions Interviewers Ask About Number of Islands
- How can you solve Number of Islands without modifying the input grid?
Use a secondary visited boolean matrix or a Disjoint Set (Union Find) data structure.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.