Count Sub Islands solution and explanation
9 more videos on this problem
Count Sub Islands - DFS - Leetcode 1905 - PythonNeetCode · 12:42 · 39K views
Count Sub Islands | Easiest Thought Process | Leetcode 1905 | codestorywithMIKcodestorywithMIK · 29:15 · 9K views
Leetcode Solution | 5791. Count Sub Islands | Practice for Online RoundsFraz · 9:25 · 5K views
Leetcode 1905. Count Sub Islands || Weekly Contest 246 || Code + Explanation walkthroughCode with Alisha · 11:33 · 5K views
1905. Count Sub Islands (Leetcode Medium)Programming Live with Larry · 9:52 · 602 views
COUNT SUB ISLANDS | LEETCODE 1905 | PYTHON BFS SOLUTIONCracking FAANG · 18:11 · 565 views
Daily Leetcode #1611: Aug 28, 2024 - 1905. Count Sub IslandsProgramming Live with Larry · 10:19 · 403 views
LeetCode 1905 - Count Sub Islands - JavaAlpha-Code · 13:42 · 190 views
Day 66 | 1905. Count Sub Islands | C++ in ArabicMaTb3a · 11:07 · 162 views
Count Sub Islands - Leetcode 1905 - DFS - PythonEffective Coder · 15:47 · 144 views
The problem
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]andgrid2[i][j]are either0or1.
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.
def dfs(grid1, grid2, i, j, is_sub_island):
if i < 0 or i >= len(grid2) or j < 0 or j >= len(grid2[0]) or grid2[i][j] == 0:
return
if grid1[i][j] == 0:
is_sub_island[0] = False
grid2[i][j] = 0
dfs(grid1, grid2, i+1, j, is_sub_island)
dfs(grid1, grid2, i-1, j, is_sub_island)
dfs(grid1, grid2, i, j+1, is_sub_island)
dfs(grid1, grid2, i, j-1, is_sub_island)
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
count = 0
for i in range(len(grid2)):
for j in range(len(grid2[0])):
if grid2[i][j] == 1:
is_sub_island = [True]
dfs(grid1, grid2, i, j, is_sub_island)
if is_sub_island[0]:
count += 1
return count
# Example usage
if __name__ == "__main__":
sol = Solution()
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]]
print(sol.countSubIslands(grid1, grid2))class Solution {
public void dfs(int[][] grid1, int[][] grid2, int i, int j, boolean[] isSubIsland) {
if (i < 0 || i >= grid2.length || j < 0 || j >= grid2[0].length || grid2[i][j] == 0) {
return;
}
if (grid1[i][j] == 0) {
isSubIsland[0] = false;
}
grid2[i][j] = 0;
dfs(grid1, grid2, i + 1, j, isSubIsland);
dfs(grid1, grid2, i - 1, j, isSubIsland);
dfs(grid1, grid2, i, j + 1, isSubIsland);
dfs(grid1, grid2, i, j - 1, isSubIsland);
}
public int countSubIslands(int[][] grid1, int[][] grid2) {
int count = 0;
for (int i = 0; i < grid2.length; i++) {
for (int j = 0; j < grid2[0].length; j++) {
if (grid2[i][j] == 1) {
boolean[] isSubIsland = {true};
dfs(grid1, grid2, i, j, isSubIsland);
if (isSubIsland[0]) {
count++;
}
}
}
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] 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}};
int[][] 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}};
System.out.println(sol.countSubIslands(grid1, grid2));
}
}#include <vector>
using namespace std;
void dfs(vector<vector<int>>& grid1, vector<vector<int>>& grid2, int i, int j, bool& isSubIsland) {
if (i < 0 || i >= grid2.size() || j < 0 || j >= grid2[0].size() || grid2[i][j] == 0) {
return;
}
if (grid1[i][j] == 0) {
isSubIsland = false;
}
grid2[i][j] = 0;
dfs(grid1, grid2, i+1, j, isSubIsland);
dfs(grid1, grid2, i-1, j, isSubIsland);
dfs(grid1, grid2, i, j+1, isSubIsland);
dfs(grid1, grid2, i, j-1, isSubIsland);
}
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
int m = grid1.size(), n = grid1[0].size(), count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
bool isSubIsland = true;
dfs(grid1, grid2, i, j, isSubIsland);
if (isSubIsland) count++;
}
}
}
return count;
}
int main() {
vector<vector<int>> 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}};
vector<vector<int>> 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}};
int result = countSubIslands(grid1, grid2);
cout << result << endl;
return 0;
}function dfs(grid1, grid2, i, j, isSubIsland) {
if (i < 0 || i >= grid2.length || j < 0 || j >= grid2[0].length || grid2[i][j] === 0) {
return;
}
if (grid1[i][j] === 0) {
isSubIsland[0] = false;
}
grid2[i][j] = 0;
dfs(grid1, grid2, i + 1, j, isSubIsland);
dfs(grid1, grid2, i - 1, j, isSubIsland);
dfs(grid1, grid2, i, j + 1, isSubIsland);
dfs(grid1, grid2, i, j - 1, isSubIsland);
}
function countSubIslands(grid1, grid2) {
let count = 0;
for (let i = 0; i < grid2.length; i++) {
for (let j = 0; j < grid2[0].length; j++) {
if (grid2[i][j] === 1) {
let isSubIsland = [true];
dfs(grid1, grid2, i, j, isSubIsland);
if (isSubIsland[0]) {
count++;
}
}
}
}
return count;
}
// Example usage
const 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]
];
const 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]
];
console.log(countSubIslands(grid1, grid2));#include <stdbool.h>
#include <stdio.h>
void dfs(int** grid1, int** grid2, int m, int n, int i, int j, bool* isSubIsland) {
if (i < 0 || i >= m || j < 0 || j >= n || grid2[i][j] == 0) {
return;
}
if (grid1[i][j] == 0) {
*isSubIsland = false;
}
grid2[i][j] = 0;
int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
for (int d = 0; d < 4; d++) {
dfs(grid1, grid2, m, n, i + dirs[d][0], j + dirs[d][1], isSubIsland);
}
}
int countSubIslands(int** grid1, int grid1Size, int* grid1ColSize, int** grid2, int grid2Size, int* grid2ColSize) {
int m = grid1Size, n = grid1ColSize[0], count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
bool isSubIsland = true;
dfs(grid1, grid2, m, n, i, j, &isSubIsland);
if (isSubIsland) count++;
}
}
}
return count;
}
int main() {
int grid1[5][5] = {{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}};
int grid2[5][5] = {{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}};
int grid1ColSize[] = {5,5,5,5,5};
int grid2ColSize[] = {5,5,5,5,5};
int* grid1Ptrs[5];
int* grid2Ptrs[5];
for(int i = 0; i < 5; i++) {
grid1Ptrs[i] = grid1[i];
grid2Ptrs[i] = grid2[i];
}
int result = countSubIslands(grid1Ptrs, 5, grid1ColSize, grid2Ptrs, 5, grid2ColSize);
printf("%d\n", result);
return 0;
}public class Solution {
public void DFS(int[][] grid1, int[][] grid2, int i, int j, ref bool isSubIsland) {
if (i < 0 || i >= grid2.Length || j < 0 || j >= grid2[0].Length || grid2[i][j] == 0) return;
if (grid1[i][j] == 0) isSubIsland = false;
grid2[i][j] = 0;
DFS(grid1, grid2, i + 1, j, ref isSubIsland);
DFS(grid1, grid2, i - 1, j, ref isSubIsland);
DFS(grid1, grid2, i, j + 1, ref isSubIsland);
DFS(grid1, grid2, i, j - 1, ref isSubIsland);
}
public int CountSubIslands(int[][] grid1, int[][] grid2) {
int m = grid2.Length, n = grid2[0].Length, count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
bool isSubIsland = true;
DFS(grid1, grid2, i, j, ref isSubIsland);
if (isSubIsland) count++;
}
}
}
return count;
}
public static void Main() {
Solution solution = new Solution();
int[][] grid1 = new int[][] {
new int[] {1, 1, 1, 0, 0},
new int[] {0, 1, 1, 1, 1},
new int[] {0, 0, 0, 0, 0},
new int[] {1, 0, 0, 0, 0},
new int[] {1, 1, 0, 1, 1}
};
int[][] grid2 = new int[][] {
new int[] {1, 1, 1, 0, 0},
new int[] {0, 0, 1, 1, 1},
new int[] {0, 1, 0, 0, 0},
new int[] {1, 0, 1, 1, 0},
new int[] {0, 1, 0, 1, 0}
};
Console.WriteLine(solution.CountSubIslands(grid1, grid2));
}
}By utilizing DFS in Python, we iterate over grid2 to identify starting points of islands, and traverse them to assess if each corresponds entirely within islands in grid1, consequently counting valid sub-islands.
Time Complexity: O(m * n).
Space Complexity: O(m * n) for recursion stack.
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.
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.rank = [0] * size
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
if self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
class Solution:
def countSubIslands(self, grid1, grid2):
m, n = len(grid1), len(grid1[0])
uf = UnionFind(m * n)
for i in range(m):
for j in range(n):
if grid1[i][j] == 1:
index = i * n + j
for direction in [(0, 1), (1, 0)]:
ni, nj = i + direction[0], j + direction[1]
if ni < m and nj < n and grid1[ni][nj] == 1:
uf.union(index, ni * n + nj)
visited = set()
count = 0
for i in range(m):
for j in range(n):
if grid2[i][j] == 1:
index = i * n + j
rootIndex = uf.find(index)
if rootIndex not in visited:
isSubIsland = True
stack = [(i, j)]
while stack:
x, y = stack.pop()
for direction in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
nx, ny = x + direction[0], y + direction[1]
if 0 <= nx < m and 0 <= ny < n and grid2[nx][ny] == 1:
grid2[nx][ny] = 0
if uf.find(nx * n + ny) != rootIndex:
isSubIsland = False
else:
stack.append((nx, ny))
if isSubIsland:
visited.add(rootIndex)
count += 1
return count
# Example usage
if __name__ == "__main__":
sol = Solution()
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]]
print(sol.countSubIslands(grid1, grid2))class UnionFind {
int[] parent;
int[] rank;
UnionFind(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
}
class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.length, n = grid1[0].length;
UnionFind uf = new UnionFind(m * n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid1[i][j] == 1) {
int index = i * n + j;
if (i + 1 < m && grid1[i + 1][j] == 1) uf.union(index, (i + 1) * n + j);
if (j + 1 < n && grid1[i][j + 1] == 1) uf.union(index, i * n + j + 1);
}
}
}
boolean[] rootVisited = new boolean[m * n];
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
boolean isSubIsland = true;
int index = i * n + j;
int rootIndex = uf.find(index);
if (!rootVisited[rootIndex]) {
for (int[] direction : new int[][] { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }) {
int ni = i + direction[0], nj = j + direction[1];
if (ni >= 0 && ni < m && nj >= 0 && nj < n && grid2[ni][nj] == 1) {
int niIndex = ni * n + nj;
if (uf.find(index) != uf.find(niIndex)) {
isSubIsland = false;
break;
}
}
}
if (isSubIsland) {
rootVisited[rootIndex] = true;
count++;
}
}
}
}
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] 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}};
int[][] 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}};
System.out.println(sol.countSubIslands(grid1, grid2));
}
}#include <vector>
using namespace std;
class UnionFind {
public:
UnionFind(int size) : parent(size), rank(size, 0) {
for (int i = 0; i < size; ++i) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
private:
vector<int> parent;
vector<int> rank;
};
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
int m = grid1.size(), n = grid1[0].size();
UnionFind uf(m * n);
auto getIndex = [&](int x, int y) -> int {
return x * n + y;
};
// Union for grid1
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid1[i][j] == 1) {
for (const auto& d : vector<pair<int, int>>{{1, 0}, {0, 1}}) {
int ni = i + d.first, nj = j + d.second;
if (ni < m && nj < n && grid1[ni][nj] == 1) {
uf.unite(getIndex(i, j), getIndex(ni, nj));
}
}
}
}
}
vector<bool> found(m * n, false);
int count = 0;
// Check for grid2
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid2[i][j] == 1) {
bool isSubIsland = true;
int root = uf.find(getIndex(i, j));
if (!found[root]) {
for (const auto& d : vector<pair<int, int>>{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) {
int ni = i + d.first, nj = j + d.second;
if (ni >= 0 && nj >= 0 && ni < m && nj < n && grid2[ni][nj] == 1) {
if (uf.find(getIndex(i, j)) != uf.find(getIndex(ni, nj))) {
isSubIsland = false;
}
}
}
if (isSubIsland) {
found[root] = true;
count++;
}
}
}
}
}
return count;
}
int main() {
vector<vector<int>> 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}};
vector<vector<int>> 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}};
cout << countSubIslands(grid1, grid2) << endl;
return 0;
}class UnionFind {
constructor(size) {
this.parent = Array(size).fill(0).map((_, index) => index);
this.rank = Array(size).fill(0);
}
find(x) {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x]);
}
return this.parent[x];
}
union(x, y) {
const rootX = this.find(x);
const rootY = this.find(y);
if (rootX !== rootY) {
if (this.rank[rootX] > this.rank[rootY]) {
this.parent[rootY] = rootX;
} else if (this.rank[rootX] < this.rank[rootY]) {
this.parent[rootX] = rootY;
} else {
this.parent[rootY] = rootX;
this.rank[rootX] += 1;
}
}
}
}
function countSubIslands(grid1, grid2) {
const m = grid1.length;
const n = grid1[0].length;
const uf = new UnionFind(m * n);
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid1[i][j] === 1) {
const index = i * n + j;
for (const [dx, dy] of [[1, 0], [0, 1]]) {
const ni = i + dx;
const nj = j + dy;
if (ni < m && nj < n && grid1[ni][nj] === 1) {
uf.union(index, ni * n + nj);
}
}
}
}
}
const rootVisited = new Set();
let count = 0;
function dfs(x, y, rootIndex) {
const stack = [[x, y]];
let isSubIsland = true;
while (stack.length > 0) {
const [i, j] = stack.pop();
for (const [dx, dy] of [[0, 1], [1, 0], [0, -1], [-1, 0]]) {
const ni = i + dx;
const nj = j + dy;
if (ni >= 0 && ni < m && nj >= 0 && nj < n && grid2[ni][nj] === 1) {
grid2[ni][nj] = 0;
if (uf.find(ni * n + nj) !== rootIndex) {
isSubIsland = false;
} else {
stack.push([ni, nj]);
}
}
}
}
return isSubIsland;
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid2[i][j] === 1) {
grid2[i][j] = 0;
const index = i * n + j;
const rootIndex = uf.find(index);
if (!rootVisited.has(rootIndex)) {
if (dfs(i, j, rootIndex)) {
rootVisited.add(rootIndex);
count++;
}
}
}
}
}
return count;
}
// Example usage
const 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]
];
const 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]
];
console.log(countSubIslands(grid1, grid2));#include <stdio.h>
#include <stdbool.h>
int find(int* parent, int x) {
if (parent[x] != x) parent[x] = find(parent, parent[x]);
return parent[x];
}
void unionSets(int* parent, int* rank, int x, int y) {
int rootX = find(parent, x);
int rootY = find(parent, y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
int countSubIslands(int** grid1, int grid1Size, int* grid1ColSize, int** grid2, int grid2Size, int* grid2ColSize) {
int m = grid1Size, n = grid1ColSize[0];
int parent[m*n], rank[m*n];
for (int i = 0; i < m * n; i++) {
parent[i] = i;
rank[i] = 0;
}
int directions[4][2] = {{1,0}, {0,1}, {-1,0}, {0,-1}};
auto getIndex = [&](int x, int y) { return x * n + y; };
// Union for grid1
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid1[i][j] == 1) {
for (int d = 0; d < 4; d++) {
int ni = i + directions[d][0], nj = j + directions[d][1];
if (ni >= 0 && nj >= 0 && ni < m && nj < n && grid1[ni][nj] == 1) {
unionSets(parent, rank, getIndex(i, j), getIndex(ni, nj));
}
}
}
}
}
int subIslandsCount = 0;
bool foundGrid1[m*n];
for (int i = 0; i < m*n; ++i) foundGrid1[i] = false;
// Check for grid2
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
bool isSubIsland = true;
for (int d = 0; d < 4; d++) {
int ni = i + directions[d][0], nj = j + directions[d][1];
if (ni >= 0 && nj >= 0 && ni < m && nj < n && grid2[ni][nj] == 1) {
if (find(parent, getIndex(i, j)) != find(parent, getIndex(ni, nj))) {
isSubIsland = false;
}
}
}
if (isSubIsland && !foundGrid1[find(parent, getIndex(i, j))]) {
foundGrid1[find(parent, getIndex(i, j))] = true;
subIslandsCount++;
}
}
}
}
return subIslandsCount;
}
int main() {
int grid1[5][5] = {{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}};
int grid2[5][5] = {{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}};
int grid1ColSize[] = {5,5,5,5,5};
int grid2ColSize[] = {5,5,5,5,5};
int* grid1Ptrs[5];
int* grid2Ptrs[5];
for(int i = 0; i < 5; i++) {
grid1Ptrs[i] = grid1[i];
grid2Ptrs[i] = grid2[i];
}
int result = countSubIslands(grid1Ptrs, 5, grid1ColSize, grid2Ptrs, 5, grid2ColSize);
printf("%d\n", result);
return 0;
}public class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) {
parent[i] = i;
rank[i] = 0;
}
}
public int Find(int x) {
if (parent[x] != x) {
parent[x] = Find(parent[x]);
}
return parent[x];
}
public void Union(int x, int y) {
int rootX = Find(x);
int rootY = Find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
}
public class Solution {
public int CountSubIslands(int[][] grid1, int[][] grid2) {
int m = grid1.Length, n = grid1[0].Length;
UnionFind uf = new UnionFind(m * n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid1[i][j] == 1) {
int index = i * n + j;
if (i + 1 < m && grid1[i + 1][j] == 1) uf.Union(index, (i + 1) * n + j);
if (j + 1 < n && grid1[i][j + 1] == 1) uf.Union(index, i * n + j + 1);
}
}
}
bool[] rootVisited = new bool[m * n];
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
int index = i * n + j;
int rootIndex = uf.Find(index);
if (!rootVisited[rootIndex]) {
bool isSubIsland = true;
var directions = new int[][] { new int[] {0, 1}, new int[] {1, 0}, new int[] {0, -1}, new int[] {-1, 0} };
var stack = new Stack<int[]>();
stack.Push(new int[] {i, j});
while (stack.Count > 0) {
var point = stack.Pop();
foreach (var dir in directions) {
int newX = point[0] + dir[0];
int newY = point[1] + dir[1];
if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid2[newX][newY] == 1) {
grid2[newX][newY] = 0;
if (uf.Find(newX * n + newY) != rootIndex) {
isSubIsland = false;
} else {
stack.Push(new int[] {newX, newY});
}
}
}
}
if (isSubIsland) {
rootVisited[rootIndex] = true;
count++;
}
}
}
}
}
return count;
}
public static void Main(string[] args) {
int[][] grid1 = {
new int[] {1, 1, 1, 0, 0},
new int[] {0, 1, 1, 1, 1},
new int[] {0, 0, 0, 0, 0},
new int[] {1, 0, 0, 0, 0},
new int[] {1, 1, 0, 1, 1}
};
int[][] grid2 = {
new int[] {1, 1, 1, 0, 0},
new int[] {0, 0, 1, 1, 1},
new int[] {0, 1, 0, 0, 0},
new int[] {1, 0, 1, 1, 0},
new int[] {0, 1, 0, 1, 0}
};
Solution sol = new Solution();
Console.WriteLine(sol.CountSubIslands(grid1, grid2));
}
}This Python implementation adopts a Union-Find strategy to align components within grid1 and aligns islands in grid2 relative to these components, allowing only completely overlapping islands to be counted as sub-islands.
Time Complexity: O(m * n * (α(m*n))).
Space Complexity: O(m * n) for holding disjoint set data.
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.
function countSubIslands(grid1: number[][], grid2: number[][]): number {
const [m, n] = [grid1.length, grid1[0].length];
let ans = 0;
const dirs: number[] = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): number => {
let ok = grid1[i][j];
grid2[i][j] = 0;
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
ok &= dfs(x, y);
}
}
return ok;
};
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; j++) {
if (grid2[i][j]) {
ans += dfs(i, j);
}
}
}
return ans;
}func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) {
m, n := len(grid1), len(grid1[0])
dirs := [5]int{-1, 0, 1, 0, -1}
var dfs func(i, j int) int
dfs = func(i, j int) int {
ok := grid1[i][j]
grid2[i][j] = 0
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && dfs(x, y) == 0 {
ok = 0
}
}
return ok
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid2[i][j] == 1 {
ans += dfs(i, j)
}
}
}
return
}Complexity comparison
| Approach | Complexity |
|---|---|
| DFS Approach | Time Complexity: O(m * n). |
| Union-Find Approach | Time Complexity: O(m * n * (α(m*n))). |
| DFS | – |
Complexity analysis
| 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 |
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.
