The "Count Sub Islands interview question" is a 2D grid problem. You are given two binary matrices, grid1 and grid2, representing land (1) and water (0). An island in grid2 is considered a "sub-island" if every single cell of that island is also part of an island in grid1. You need to count the total number of such sub-islands in grid2.
Companies like Amazon and Google use the "Count Sub Islands coding problem" to test a candidate's proficiency with Graph Traversal (DFS/BFS). It adds a layer of complexity to the standard "Number of Islands" problem by requiring you to validate a condition across two different grids simultaneously. It evaluations your ability to maintain state across multiple cells during a traversal.
This problem is solved using the Flood Fill or DFS/BFS pattern.
grid2.grid2 that hasn't been visited, start a DFS/BFS to explore the entire island.grid2, check each cell against grid1[r][c].
grid1[r][c] is 0, then this island in grid2 is NOT a sub-island.grid1.grid1:
1 1 1
1 0 0
grid2:
1 1 0
0 0 1
grid2: {(0,0), (0,1)}. Both are 1 in grid1. Sub-island! (Count = 1).grid2: {(1,2)}. But grid1[1][2] is 0. Not a sub-island.
Result: 1.grid1 is found to be 0. This is a mistake because you need to visit and "sink" all parts of the island in grid2 to avoid re-discovering them later in the loop.grid2 against grid1 incorrectly or swapping their roles.Master the "Island Pattern." Problems involving connected components in a matrix are extremely common. Practice implementing DFS both recursively and iteratively, as some interviewers may ask about stack limits for large grids.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Closed Islands | Medium | Solve | |
| Detect Cycles in 2D Grid | Medium | Solve | |
| Maximum Number of Fish in a Grid | Medium | Solve | |
| Number of Enclaves | Medium | Solve | |
| Max Area of Island | Medium | Solve |