Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Union-Find
[[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]] [[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]]
[[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]] [[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]]
number-of-islands)number-of-distinct-islands)find-all-groups-of-farmland)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1905: Count Sub Islands
class Solution {
private final int[] dirs = {-1, 0, 1, 0, -1};
private int[][] grid1;
private int[][] grid2;
private int m;
private int n;
public int countSubIslands(int[][] grid1, int[][] grid2) {
m = grid1.length;
n = grid1[0].length;
this.grid1 = grid1;
this.grid2 = grid2;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid2[i][j] == 1) {
ans += dfs(i, j);
}
}
}
return ans;
}
private int dfs(int i, int j) {
int ok = grid1[i][j];
grid2[i][j] = 0;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) {
ok &= dfs(x, y);
}
}
return ok;
}
}
// Accepted solution for LeetCode #1905: Count Sub Islands
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
}
# Accepted solution for LeetCode #1905: Count Sub Islands
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
ok = grid1[i][j]
grid2[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y):
ok = 0
return ok
m, n = len(grid1), len(grid1[0])
dirs = (-1, 0, 1, 0, -1)
return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])
// Accepted solution for LeetCode #1905: Count Sub Islands
/**
* [1905] Count Sub Islands
*
* 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/test1.png" style="width: 493px; height: 205px;" />
* 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" style="width: 491px; height: 201px;" />
* 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.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/count-sub-islands/
// discuss: https://leetcode.com/problems/count-sub-islands/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn count_sub_islands(grid1: Vec<Vec<i32>>, grid2: Vec<Vec<i32>>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1905_example_1() {
let grid1 = vec![
vec![1, 1, 1, 0, 0],
vec![0, 1, 1, 1, 1],
vec![0, 0, 0, 0, 0],
vec![1, 0, 0, 0, 0],
vec![1, 1, 0, 1, 1],
];
let grid2 = vec![
vec![1, 1, 1, 0, 0],
vec![0, 0, 1, 1, 1],
vec![0, 1, 0, 0, 0],
vec![1, 0, 1, 1, 0],
vec![0, 1, 0, 1, 0],
];
let result = 3;
assert_eq!(Solution::count_sub_islands(grid1, grid2), result);
}
#[test]
#[ignore]
fn test_1905_example_2() {
let grid1 = vec![
vec![1, 0, 1, 0, 1],
vec![1, 1, 1, 1, 1],
vec![0, 0, 0, 0, 0],
vec![1, 1, 1, 1, 1],
vec![1, 0, 1, 0, 1],
];
let grid2 = vec![
vec![0, 0, 0, 0, 0],
vec![1, 1, 1, 1, 1],
vec![0, 1, 0, 1, 0],
vec![0, 1, 0, 1, 0],
vec![1, 0, 0, 0, 1],
];
let result = 2;
assert_eq!(Solution::count_sub_islands(grid1, grid2), result);
}
}
// Accepted solution for LeetCode #1905: Count Sub Islands
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;
}
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.