Backend Engineering
Senior
programming
LeetCode #200 - Number of Islands: Given a 2D grid of '1's (land) and '0's (water), count 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.
Input
- A 2D grid represented as a list of lists.
Output
- An integer representing the number of islands.
Example
Input:
[[1,1,0,0,0],
[1,1,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1]]
Output:
3
Constraints
- 0 <= grid.length, grid[i].length <= 300
```
## Approach
A typical approach for this problem is using DFS or BFS. We will iterate through each cell in the grid, and when we find '1', we initiate a DFS/BFS to mark all connected '1's as visited. We count how many times we start this process to find the number of islands.
## Complexity
**Time:** O(n*m), where n is the number of rows and m is the number of columns in the grid.
**Space:** O(n*m) for the visited structure.
## Trade-offs
- DFS can lead to stack overflow in case of very deep recursions.
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free
More Backend Engineering Interview Prep
Describe a time when you had to optimize a backend service that was performing poorly. What steps did you take to analyze and resolve the issue?
Backend Engineering · Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.