Count Sub Islands solution explained
Count Sub Islands hands you two grids of the same size and asks how many islands in the second grid sit entirely on land in the first grid. Flood-fill each island of the second grid and keep a flag that turns false as soon as any of its cells is water in the first grid, but finish the fill anyway so the island is fully marked. Every cell is visited once, so the whole job is O(rows × cols).
By Evin JohnPublished 9 min read
The problem in plain words
Picture two maps of the same area, drawn at different times. Each map is a grid where 1 means land and 0 means water, and land cells that share a side form an island. Call the older map A and the newer one B. An island of B counts as a sub-island if every one of its cells is also land on map A. Return how many islands of B qualify.
A: 1 1 0 1 1 B: 1 1 0 0 1
1 0 0 1 1 0 0 0 1 1
0 0 1 1 0 0 1 1 1 0
1 0 1 0 0 1 0 0 0 1B has four islands. The pair of cells at the top left is land in A, so it counts. The single cell at the bottom left is land in A, so it counts too. The bottom right cell is water in A, so it does not. The large snake of six cells from the top right down to row 2, column 1 is mostly land in A, but row 2, column 1 is water there, so the whole island fails. The answer is 2.
What the interviewer is checking
This is a flood fill with one extra condition, so the interviewer wants to see whether you can carry state through a traversal without breaking the traversal. Strong candidates say early that islands come from B alone, that A is only a lookup, and that a failed check must not cut the fill short. They also mention recursion depth, because a grid that is all land makes a recursive fill go as deep as the grid is large.
Straightforward first: collect the island, then check it
The clearest first version separates the two jobs. Find an unvisited land cell of B, collect every cell of its island into a list, and only then ask whether all of them are land in A. It is already linear, since each cell is collected once and checked once. Its only cost over the final version is the extra list per island, which can be as large as the grid. Many interviewers are happy with this; the flag version below is a small refinement you can offer once it works.
def count_sub_islands_collect(main, other):
rows, cols = len(main), len(main[0])
seen = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if other[r][c] != 1 or seen[r][c]:
continue
# collect the whole island of other that contains (r, c)
island, stack = [], [(r, c)]
seen[r][c] = True
while stack:
cr, cc = stack.pop()
island.append((cr, cc))
for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
if 0 <= nr < rows and 0 <= nc < cols and other[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
# then check every collected cell against main
if all(main[ir][ic] == 1 for ir, ic in island):
count += 1
return countOne pass with a flag
Drop the list and keep a single boolean per island. Start it as true. Each time the fill pops a cell, look up the same position in A; if it is water, set the flag to false and carry on. When the stack empties, the island is fully marked as seen, and the flag tells you whether to count it. The pattern is a flood fill that reports a property of the whole component, the same shape you would use to measure an island's area or check whether it touches the border.
def count_sub_islands(main, other):
rows, cols = len(main), len(main[0])
seen = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if other[r][c] != 1 or seen[r][c]:
continue
inside = True # stays True only if every cell is land in main
stack = [(r, c)]
seen[r][c] = True
while stack:
cr, cc = stack.pop()
if main[cr][cc] == 0:
inside = False # keep going: the rest of the island must be marked
for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
if 0 <= nr < rows and 0 <= nc < cols and other[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
if inside:
count += 1
return countfunction countSubIslands(main, other) {
const rows = main.length;
const cols = main[0].length;
const seen = other.map((row) => row.map(() => false));
const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let count = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (other[r][c] !== 1 || seen[r][c]) continue;
let inside = true;
const stack = [[r, c]];
seen[r][c] = true;
while (stack.length > 0) {
const [cr, cc] = stack.pop();
if (main[cr][cc] === 0) inside = false; // note it, but finish the island
for (const [dr, dc] of moves) {
const nr = cr + dr, nc = cc + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols &&
other[nr][nc] === 1 && !seen[nr][nc]) {
seen[nr][nc] = true;
stack.push([nr, nc]);
}
}
}
if (inside) count++;
}
}
return count;
}Why stopping early breaks it
Take a one-row case: A is 1 0 1 and B is 1 1 1. B has one island of three cells, and its middle cell is water in A, so the answer is 0. A fill that starts at column 0 and returns the moment it meets column 1 never reaches column 2. The outer loop later starts a fresh fill there, that one-cell piece is land in A, and it gets counted, so the function returns 1. (In the larger example above the bad cell happens to be the last one reached, which hides the bug; tests need a case like this one.) In a recursive version the same bug shows up as writing return dfs(a) and dfs(b), where the and skips the second call once the first returns false. Evaluate every neighbor, then combine.
A second approach some people prefer: first sink every island of B that has any cell over water in A, then count the islands that remain with an ordinary island counter. It visits cells twice but splits the logic into two familiar pieces.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Collect each island, then check it | O(R·C) | O(R·C) for the seen grid, stack and island list |
| Flood fill with a flag | O(R·C) | O(R·C) for the seen grid and stack |
| Sink the failing islands, then count | O(R·C), two passes | O(R·C), or O(stack) if B may be modified |
Edge cases to test
- B is all water: the answer is 0, whatever A holds.
- A is all land: every island of B counts, so the answer is B's island count.
- An island of B that fails only at its last visited cell: the flag must still flip.
- One huge island covering the grid: use an explicit stack, since a recursive fill can exceed the default recursion limit in Python.
- Land touching only at corners: separate islands, because moves are up, down, left and right.
Mistakes that cost points
- Building islands from A instead of B, or from cells that are land in both grids, which splits B's islands into pieces.
- Returning from the fill as soon as a water cell in A is found.
- Short-circuit logic in a recursive version, so some neighbors are never visited.
- Marking cells as seen when popped instead of when pushed, which lets the same cell enter the stack several times.
- Changing the input grids to mark visits without asking whether that is allowed.
Follow-up questions
- Count islands of B that overlap A at all. Flip the flag logic: start false and set it true on the first land cell in A.
- Return the size of the largest sub-island. Count cells during the fill and keep the best size among islands that pass.
- The grids arrive one row at a time. Use a union-find over the current and previous row, carrying a pass or fail bit per set.
- Eight-way connectivity. Add the four diagonal moves; nothing else changes.
Saying it out loud
Fictional example
- Candidate
- The islands come from the second grid only. The first grid is just a lookup that says whether each cell is allowed.
- Candidate
- So I flood-fill each island of the second grid with a stack, and keep one flag. If any cell is water in the first grid, the flag goes false, but I keep filling so the whole island is marked.
- Candidate
- When the fill ends I count the island if the flag is still true. Each cell is pushed once, so it is linear in the grid size.
Related walkthroughs
Number of Islands is the plain flood fill this builds on. Making A Large Island labels islands and their sizes before changing one cell, and Shortest Bridge fills one island and then searches outward from it. For a graph version of "a whole component either passes or fails", see Find Eventual Safe States. The coding problems hub has the full list.
Practicing two-grid problems with Natively
Two-grid problems are easy to misread under pressure. In a practice session on Mac or Windows, Natively can read both grids from a screenshot and talk through which one defines the islands, and it can suggest code for the flag-carrying fill when you ask. Because the session is transcribed, you can reread whether you explained the never-stop-early rule before you wrote it. The AI interview assistant page describes the coding features.
Questions people ask
How do you solve Count Sub Islands?
Flood-fill each island of the second grid. Keep a flag that turns false if any of its cells is water in the first grid, finish the fill anyway, and count the island if the flag is still true.
Why should the flood fill not stop early in Count Sub Islands?
Stopping leaves part of the island unvisited. The outer loop later starts a new fill from those cells, and that partial island can be counted by mistake.
What is the time complexity of Count Sub Islands?
O(rows × cols), because every cell is pushed onto the stack at most once.
Which grid defines the islands in Count Sub Islands?
The second grid. The first grid is only used to check whether each cell of those islands is land.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
