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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.
The grid is said to be connected if we have exactly one island, otherwise is said disconnected.
In one day, we are allowed to change any single land cell (1) into a water cell (0).
Return the minimum number of days to disconnect the grid.
Example 1:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
Example 2:
Input: grid = [[1,1]] Output: 2 Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 30grid[i][j] is either 0 or 1.Problem summary: You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[0,1,1,0],[0,1,1,0],[0,0,0,0]]
[[1,1]]
disconnect-path-in-a-binary-matrix-by-at-most-one-flip)minimum-runes-to-add-to-cast-spell)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1568: Minimum Number of Days to Disconnect Island
class Solution {
private static final int[] DIRS = new int[] {-1, 0, 1, 0, -1};
private int[][] grid;
private int m;
private int n;
public int minDays(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
if (count() != 1) {
return 0;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
grid[i][j] = 0;
if (count() != 1) {
return 1;
}
grid[i][j] = 1;
}
}
}
return 2;
}
private int count() {
int cnt = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
dfs(i, j);
++cnt;
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 2) {
grid[i][j] = 1;
}
}
}
return cnt;
}
private void dfs(int i, int j) {
grid[i][j] = 2;
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 && grid[x][y] == 1) {
dfs(x, y);
}
}
}
}
// Accepted solution for LeetCode #1568: Minimum Number of Days to Disconnect Island
func minDays(grid [][]int) int {
m, n := len(grid), len(grid[0])
dirs := []int{-1, 0, 1, 0, -1}
var dfs func(i, j int)
dfs = func(i, j int) {
grid[i][j] = 2
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 {
dfs(x, y)
}
}
}
count := func() int {
cnt := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
dfs(i, j)
cnt++
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 2 {
grid[i][j] = 1
}
}
}
return cnt
}
if count() != 1 {
return 0
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
grid[i][j] = 0
if count() != 1 {
return 1
}
grid[i][j] = 1
}
}
}
return 2
}
# Accepted solution for LeetCode #1568: Minimum Number of Days to Disconnect Island
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
if self.count(grid) != 1:
return 0
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = 0
if self.count(grid) != 1:
return 1
grid[i][j] = 1
return 2
def count(self, grid):
def dfs(i, j):
grid[i][j] = 2
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
dfs(x, y)
m, n = len(grid), len(grid[0])
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
dfs(i, j)
cnt += 1
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
grid[i][j] = 1
return cnt
// Accepted solution for LeetCode #1568: Minimum Number of Days to Disconnect Island
struct Solution;
impl Solution {
fn min_days(mut grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let m = grid[0].len();
if Self::islands(&grid, n, m) != 1 {
return 0;
}
for i in 0..n {
for j in 0..m {
if grid[i][j] == 1 {
grid[i][j] = 0;
if Self::islands(&grid, n, m) > 1 {
return 1;
}
grid[i][j] = 1;
}
}
}
2
}
fn islands(grid: &[Vec<i32>], n: usize, m: usize) -> i32 {
let mut visited = vec![vec![false; m]; n];
let mut res = 0;
for i in 0..n {
for j in 0..m {
if !visited[i][j] && grid[i][j] == 1 {
res += 1;
visited[i][j] = true;
Self::dfs(i, j, &mut visited, grid, n, m);
}
}
}
res
}
fn dfs(
i: usize,
j: usize,
visited: &mut Vec<Vec<bool>>,
grid: &[Vec<i32>],
n: usize,
m: usize,
) {
if i > 0 && grid[i - 1][j] == 1 && !visited[i - 1][j] {
visited[i - 1][j] = true;
Self::dfs(i - 1, j, visited, grid, n, m);
}
if j > 0 && grid[i][j - 1] == 1 && !visited[i][j - 1] {
visited[i][j - 1] = true;
Self::dfs(i, j - 1, visited, grid, n, m);
}
if i + 1 < n && grid[i + 1][j] == 1 && !visited[i + 1][j] {
visited[i + 1][j] = true;
Self::dfs(i + 1, j, visited, grid, n, m);
}
if j + 1 < m && grid[i][j + 1] == 1 && !visited[i][j + 1] {
visited[i][j + 1] = true;
Self::dfs(i, j + 1, visited, grid, n, m);
}
}
}
#[test]
fn test() {
let grid = vec_vec_i32![[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]];
let res = 2;
assert_eq!(Solution::min_days(grid), res);
let grid = vec_vec_i32![[1, 1]];
let res = 2;
assert_eq!(Solution::min_days(grid), res);
let grid = vec_vec_i32![[1, 0, 1, 0]];
let res = 0;
assert_eq!(Solution::min_days(grid), res);
let grid = vec_vec_i32![
[1, 1, 0, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1]
];
let res = 1;
assert_eq!(Solution::min_days(grid), res);
let grid = vec_vec_i32![
[1, 1, 0, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 1, 1, 1]
];
let res = 2;
assert_eq!(Solution::min_days(grid), res);
}
// Accepted solution for LeetCode #1568: Minimum Number of Days to Disconnect Island
function minDays(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
const dfs = (i: number, j: number) => {
if (i < 0 || m <= i || j < 0 || n <= j || [0, 2].includes(grid[i][j])) return;
grid[i][j] = 2;
const dir = [-1, 0, 1, 0, -1];
for (let k = 0; k < 4; k++) {
const [y, x] = [i + dir[k], j + dir[k + 1]];
dfs(y, x);
}
};
const count = () => {
let c = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
dfs(i, j);
c++;
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 2) {
grid[i][j] = 1;
}
}
}
return c;
};
if (count() !== 1) return 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
grid[i][j] = 0;
if (count() !== 1) return 1;
grid[i][j] = 1;
}
}
}
return 2;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
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.