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 an m x n matrix grid and a positive integer k. An island is a group of positive integers (representing land) that are 4-directionally connected (horizontally or vertically).
The total value of an island is the sum of the values of all cells in the island.
Return the number of islands with a total value divisible by k.
Example 1:
Input: grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5
Output: 2
Explanation:
The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.
Example 2:
Input: grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3
Output: 6
Explanation:
The grid contains six islands, each with a total value that is divisible by 3.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 1050 <= grid[i][j] <= 1061 <= k <= 106Problem summary: You are given an m x n matrix grid and a positive integer k. An island is a group of positive integers (representing land) that are 4-directionally connected (horizontally or vertically). The total value of an island is the sum of the values of all cells in the island. Return the number of islands with a total value divisible by k.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Union-Find
[[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]] 5
[[3,0,3,0],[0,3,0,3],[3,0,3,0]] 3
number-of-islands)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
class Solution {
private int m;
private int n;
private int[][] grid;
private final int[] dirs = {-1, 0, 1, 0, -1};
public int countIslands(int[][] grid, int k) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] > 0 && dfs(i, j) % k == 0) {
++ans;
}
}
}
return ans;
}
private long dfs(int i, int j) {
long s = grid[i][j];
grid[i][j] = 0;
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) {
s += dfs(x, y);
}
}
return s;
}
}
// Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
func countIslands(grid [][]int, k int) (ans int) {
m, n := len(grid), len(grid[0])
dirs := []int{-1, 0, 1, 0, -1}
var dfs func(i, j int) int
dfs = func(i, j int) int {
s := grid[i][j]
grid[i][j] = 0
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0 {
s += dfs(x, y)
}
}
return s
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] > 0 && dfs(i, j)%k == 0 {
ans++
}
}
}
return
}
# Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
class Solution:
def countIslands(self, grid: List[List[int]], k: int) -> int:
def dfs(i: int, j: int) -> int:
s = grid[i][j]
grid[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y]:
s += dfs(x, y)
return s
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] and dfs(i, j) % k == 0:
ans += 1
return ans
// Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
// class Solution {
// private int m;
// private int n;
// private int[][] grid;
// private final int[] dirs = {-1, 0, 1, 0, -1};
//
// public int countIslands(int[][] grid, int k) {
// m = grid.length;
// n = grid[0].length;
// this.grid = grid;
// int ans = 0;
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// if (grid[i][j] > 0 && dfs(i, j) % k == 0) {
// ++ans;
// }
// }
// }
// return ans;
// }
//
// private long dfs(int i, int j) {
// long s = grid[i][j];
// grid[i][j] = 0;
// for (int d = 0; d < 4; ++d) {
// int x = i + dirs[d], y = j + dirs[d + 1];
// if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) {
// s += dfs(x, y);
// }
// }
// return s;
// }
// }
// Accepted solution for LeetCode #3619: Count Islands With Total Value Divisible by K
function countIslands(grid: number[][], k: number): number {
const m = grid.length,
n = grid[0].length;
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): number => {
let s = grid[i][j];
grid[i][j] = 0;
for (let d = 0; d < 4; d++) {
const x = i + dirs[d],
y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) {
s += dfs(x, y);
}
}
return s;
};
let ans = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] > 0 && dfs(i, j) % k === 0) {
ans++;
}
}
}
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.