You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.
Return the number of islands in grid2 that are considered sub-islands.
Example 1:
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]] Output: 3 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
Example 2:
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]] Output: 2 Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
Constraints:
m == grid1.length == grid2.lengthn == grid1[i].length == grid2[i].length1 <= m, n <= 500grid1[i][j] and grid2[i][j] are either 0 or 1.Problem Overview: You are given two binary matrices grid1 and grid2. An island is a group of connected 1s (4-directionally). A sub-island exists when every land cell of an island in grid2 lies on land in the same position of grid1. The task is to count how many islands in grid2 are completely contained within islands of grid1.
Approach 1: DFS Flood Fill (O(m * n) time, O(m * n) space)
This approach treats each island in grid2 as a connected component and validates whether all its cells also correspond to land in grid1. Iterate through the matrix, and whenever you find an unvisited land cell in grid2, run a Depth‑First Search. During the DFS traversal, mark cells as visited and check the same position in grid1. If any cell of the explored island overlaps with water in grid1, the entire island cannot be a sub‑island. Maintain a boolean flag while exploring neighbors (up, down, left, right). If the flag remains true after the traversal, increment the result.
This works because DFS explores every cell of the island exactly once while validating the constraint. The grid is scanned once, and each cell participates in at most one DFS traversal. Time complexity is O(m * n). Space complexity is O(m * n) in the worst case due to recursion stack or visited marking. This approach directly applies standard graph traversal patterns used in Depth-First Search and grid problems involving a matrix.
Approach 2: Union-Find (Disjoint Set) (O(m * n * α(n)) time, O(m * n) space)
The Union-Find approach models each land cell as a node in a disjoint-set structure. First build connected components for islands in grid2 by unioning adjacent land cells. After building the sets, iterate through all land cells again and check whether any cell in a component overlaps with water in grid1. If that happens, mark the root of that component as invalid. Finally, count the number of distinct roots representing islands that were never marked invalid.
Union-Find is useful when you want explicit connected component management and fast merges using path compression and union by rank. The amortized complexity per operation is nearly constant (α(n)). Overall complexity becomes O(m * n * α(n)) time and O(m * n) space. This method is a strong example of the Union Find pattern commonly used in connectivity problems.
Recommended for interviews: The DFS flood-fill approach is the most expected solution. It is straightforward, easy to implement, and clearly shows understanding of grid traversal using DFS or BFS. Interviewers typically prefer this method because it validates each island during traversal with minimal overhead. The Union-Find solution demonstrates deeper knowledge of disjoint set structures and is useful when problems require dynamic connectivity or component merging.
This approach uses Depth-First Search (DFS) to explore each island in grid2, checking if it matches an area in grid1. We iterate through each cell in grid2, initiating a DFS whenever we encounter land (1). During DFS, we verify if the entire island in grid2 can be found in grid1. If during exploration, we encounter a cell that is 1 in grid2 but 0 in grid1, we mark it as not a sub-island.
We first traverse all cells in grid2. Upon encountering a cell that is part of an island (i.e., its value is 1), we start a DFS to explore the entire structure connected to this cell. During this DFS, for every cell in the current island of grid2, we check if corresponding cells in grid1 are also land. If we find a water cell (0) in grid1 where there's land in grid2, we set isSubIsland to false. If DFS completes and isSubIsland remains true, we increment our count of sub-islands.
Time Complexity: O(m * n), where m and n are the dimensions of the grids, as each cell is visited a constant number of times.
Space Complexity: O(1) additional space not counting input and stack space for recursion.
This approach uses the Union-Find data structure to efficiently group connected islands. By initially identifying all islands in both grids, we can ascertain the sub-islands by ensuring that connected components (islands) in grid2 are completely represented within connected components in grid1.
This C solution uses a Union-Find (Disjoint Set Union) to connect land cells into islands for grid1 and checks consistency for grid2. Islands in grid2 are counted as sub-islands only if each forms a connected component fully within an island in grid1.
Time Complexity: O(m * n * (α(m*n))), where α is the Inverse Ackermann function, a very slow-growing function.
Space Complexity: O(m * n) to store the parent and rank arrays.
We can traverse each cell (i, j) in the matrix grid2. If the value of the cell is 1, we start a depth-first search from this cell, set the value of all cells connected to this cell to 0, and record whether the corresponding cell in grid1 is also 1 for all cells connected to this cell. If it is 1, it means that this cell is also an island in grid1, otherwise it is not. Finally, we count the number of sub-islands in grid2.
The time complexity is O(m times n), and the space complexity is O(m times n). Here, m and n are the number of rows and columns of the matrices grid1 and grid2, respectively.
Python
Java
C++
Go
TypeScript
JavaScript
| Approach | Complexity |
|---|---|
| DFS Approach | Time Complexity: O(m * n), where m and n are the dimensions of the grids, as each cell is visited a constant number of times. |
| Union-Find Approach | Time Complexity: O(m * n * (α(m*n))), where α is the Inverse Ackermann function, a very slow-growing function. |
| DFS | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| DFS / Flood Fill | O(m * n) | O(m * n) | Best general solution for grid traversal problems and interview settings |
| Union-Find (Disjoint Set) | O(m * n * α(n)) | O(m * n) | Useful when managing connected components or solving dynamic connectivity problems |
Count Sub Islands - DFS - Leetcode 1905 - Python • NeetCode • 38,541 views views
Watch 9 more video solutions →Practice Count Sub Islands with our built-in code editor and test cases.
Practice on FleetCode