200. Number of Islands
mediumAsked at Juniper NetworksCount connected components in a 2D grid using BFS or DFS. Juniper asks this because connected-component analysis in graphs is the foundation of network topology discovery — finding isolated subnetworks, counting autonomous systems reachable from a border router, and flood-fill-based link-state calculation all follow this pattern.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Juniper Networks loops.
- Glassdoor (2026-Q1)— Reported in Juniper SWE onsite reports across multiple teams as a high-frequency graph traversal problem.
- Blind (2025-12)— One of the most cited Juniper medium problems in interview prep threads, especially for systems and networking roles.
Problem
Given an m x n 2D binary 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 surrounded by water.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j] is '0' or '1'.
Examples
Example 1
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]1Explanation: One large connected landmass.
Example 2
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]3Explanation: Three separate islands.
Approaches
1. DFS — mark visited in-place
Iterate over every cell. When a '1' is found, increment the island count and DFS to mark all connected land cells as visited (set to '0' or '2').
- Time
- O(m * n)
- Space
- O(m * n) worst-case call stack
function numIslands(grid) {
let count = 0;
const rows = grid.length, cols = grid[0].length;
function dfs(r, c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] !== '1') return;
grid[r][c] = '0'; // mark visited
dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === '1') { count++; dfs(r, c); }
}
}
return count;
}Tradeoff: O(m*n) time. In-place marking avoids a visited array. DFS can overflow the stack for a 300x300 all-land grid (90,000 frames). For that case, prefer BFS.
2. BFS — iterative, no stack overflow risk
Same idea but use a queue. Start BFS from each unvisited '1' cell, marking neighbors as visited when enqueued.
- Time
- O(m * n)
- Space
- O(min(m, n)) queue — diagonal wave front
function numIslands(grid) {
let count = 0;
const rows = grid.length, cols = grid[0].length;
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== '1') continue;
count++;
const queue = [[r, c]];
grid[r][c] = '0';
while (queue.length) {
const [cr, cc] = queue.shift();
for (const [dr, dc] of dirs) {
const nr = cr + dr, nc = cc + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === '1') {
grid[nr][nc] = '0';
queue.push([nr, nc]);
}
}
}
}
}
return count;
}Tradeoff: O(m*n) time, O(min(m,n)) queue space for the BFS wavefront. Preferred by Juniper for production use because it avoids recursive call stack limitations — critical in embedded networking OS environments.
Juniper Networks-specific tips
Mention the stack-overflow risk of DFS on a large all-land grid and proactively pivot to BFS — this shows production systems thinking that Juniper values. Connect the problem to network topology: 'This is equivalent to counting the number of disconnected subnetworks in a topology map where adjacency represents a physical link.' Juniper will also ask about Union-Find as a third approach — know the tradeoffs.
Common mistakes
- Marking a cell as visited after dequeuing instead of when enqueuing — can cause the same cell to be enqueued multiple times.
- Not checking bounds before accessing grid[nr][nc] — causes index out-of-bounds errors.
- Using a separate visited array — correct but uses O(m*n) extra space. Mutating the grid directly is more space-efficient.
- Forgetting diagonal neighbors are not connected — this problem uses 4-directional (not 8-directional) adjacency.
Follow-up questions
An interviewer at Juniper Networks may pivot to one of these next:
- Max Area of Island (LC 695) — find the island with the greatest number of cells.
- Number of Connected Components in a Graph (LC 323) — general graph instead of a 2D grid.
- How would you find the number of isolated subnetworks in a network topology graph?
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why mark cells visited when enqueuing, not when dequeuing?
If you mark when dequeuing, the same cell can be added to the queue multiple times before it is processed. Marking when enqueuing prevents redundant processing.
Does mutating the grid cause issues?
In an interview, clarify with the interviewer whether you can modify the input. If not, use a separate boolean visited array. In competitive settings, in-place mutation is standard.
What is the space complexity of BFS?
The queue holds at most O(min(m,n)) cells at a time — the BFS wavefront expands diagonally and its width is bounded by the shorter grid dimension.
Practice these live with InterviewChamp.AI
Drill Number of Islands and other Juniper Networks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →