Skip to main content

Count Sub Islands - Solution & Explanation

MediumArrayDepth-First SearchBreadth-First SearchUnion Find26 min readAsked at: Amazon, DoorDash, Google +2
Practice this problem

Problem Statement

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.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • grid1[i][j] and grid2[i][j] are either 0 or 1.

Approach Overview

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.

Approach 1: DFS Approach

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 2: Union-Find Approach

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 3: DFS

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.

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
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.
Space Complexity: O(1) additional space not counting input and stack space for recursion.

Union-Find Approach

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.

DFS

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
DFS / Flood FillO(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

Video Solution

Count Sub Islands - DFS - Leetcode 1905 - PythonNeetCode39,221 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Sub Islands easy or hard?
Count Sub Islands is rated Medium difficulty. The challenge lies in validating entire connected components rather than just counting islands. Candidates must combine grid traversal with a logical condition that invalidates an island when any cell overlaps water in grid1.
Count Sub Islands Python/Java solution
Python and Java implementations typically use DFS recursion or an explicit stack to explore each island in grid2. During traversal, the algorithm checks corresponding cells in grid1 to confirm whether the island remains valid. Both implementations achieve O(m*n) time complexity.
How to solve Count Sub Islands in O(n)?
Treat the grid as a graph and run DFS or BFS on each unvisited land cell in grid2. While exploring the island, verify that every corresponding cell in grid1 is also land. Since each cell is processed once, the total time complexity becomes O(m*n).
What is the best approach for Count Sub Islands?
The DFS flood fill approach is the most commonly used solution. Traverse each island in grid2 and verify that every visited cell corresponds to land in grid1. If any cell overlaps water in grid1, the island is invalid. This approach runs in O(m*n) time and is typically expected in coding interviews.
Is Count Sub Islands asked at Google/Amazon/Meta?
Grid traversal and island-counting variations frequently appear in interviews at companies like Amazon, Google, and Meta. Problems involving DFS/BFS on matrices, including island validation or counting connected components, are common interview patterns.
What data structure is used in Count Sub Islands?
The main structures used are recursion or stacks/queues for DFS or BFS traversal, along with the input grid acting as the graph. Another valid approach uses the Union-Find (Disjoint Set) data structure to track connected components efficiently.
What is the time complexity of Count Sub Islands?
The optimal solution runs in O(m*n) time where m and n are the grid dimensions. Each cell is visited at most once during DFS or BFS traversal. The Union-Find approach has a similar complexity of O(m*n * α(n)), where α is the inverse Ackermann function, which grows extremely slowly.

Ready to solve this problem?

Practice Count Sub Islands with our built-in code editor and test cases.

Practice on FleetCode