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.
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Example 1:
Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]] Output: 2 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2.
Example 2:
Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]] Output: 1 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1.
Example 3:
Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]] Output: 3 Explanation: The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3.
Constraints:
2 <= row, col <= 2 * 1044 <= row * col <= 2 * 104cells.length == row * col1 <= ri <= row1 <= ci <= colcells are unique.Problem summary: There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Union-Find
2 2 [[1,1],[2,1],[1,2],[2,2]]
2 2 [[1,1],[1,2],[2,1],[2,2]]
3 3 [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]
bricks-falling-when-hit)escape-the-spreading-fire)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1970: Last Day Where You Can Still Cross
class Solution {
private int[][] cells;
private int m;
private int n;
public int latestDayToCross(int row, int col, int[][] cells) {
int l = 1, r = cells.length;
this.cells = cells;
this.m = row;
this.n = col;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
private boolean check(int k) {
int[][] g = new int[m][n];
for (int i = 0; i < k; i++) {
g[cells[i][0] - 1][cells[i][1] - 1] = 1;
}
final int[] dirs = {-1, 0, 1, 0, -1};
Deque<int[]> q = new ArrayDeque<>();
for (int j = 0; j < n; j++) {
if (g[0][j] == 0) {
q.offer(new int[] {0, j});
g[0][j] = 1;
}
}
while (!q.isEmpty()) {
int[] p = q.poll();
int x = p[0], y = p[1];
if (x == m - 1) {
return true;
}
for (int i = 0; i < 4; i++) {
int nx = x + dirs[i], ny = y + dirs[i + 1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && g[nx][ny] == 0) {
q.offer(new int[] {nx, ny});
g[nx][ny] = 1;
}
}
}
return false;
}
}
// Accepted solution for LeetCode #1970: Last Day Where You Can Still Cross
func latestDayToCross(row int, col int, cells [][]int) int {
l, r := 1, len(cells)
dirs := [5]int{-1, 0, 1, 0, -1}
check := func(k int) bool {
g := make([][]int, row)
for i := range g {
g[i] = make([]int, col)
}
for i := 0; i < k; i++ {
g[cells[i][0]-1][cells[i][1]-1] = 1
}
q := [][2]int{}
for j := 0; j < col; j++ {
if g[0][j] == 0 {
g[0][j] = 1
q = append(q, [2]int{0, j})
}
}
for len(q) > 0 {
x, y := q[0][0], q[0][1]
q = q[1:]
if x == row-1 {
return true
}
for i := 0; i < 4; i++ {
nx, ny := x+dirs[i], y+dirs[i+1]
if nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] == 0 {
g[nx][ny] = 1
q = append(q, [2]int{nx, ny})
}
}
}
return false
}
for l < r {
mid := (l + r + 1) >> 1
if check(mid) {
l = mid
} else {
r = mid - 1
}
}
return l
}
# Accepted solution for LeetCode #1970: Last Day Where You Can Still Cross
class Solution:
def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
def check(k: int) -> bool:
g = [[0] * col for _ in range(row)]
for i, j in cells[:k]:
g[i - 1][j - 1] = 1
q = [(0, j) for j in range(col) if g[0][j] == 0]
for x, y in q:
if x == row - 1:
return True
for a, b in pairwise(dirs):
nx, ny = x + a, y + b
if 0 <= nx < row and 0 <= ny < col and g[nx][ny] == 0:
q.append((nx, ny))
g[nx][ny] = 1
return False
n = row * col
l, r = 1, n
dirs = (-1, 0, 1, 0, -1)
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l
// Accepted solution for LeetCode #1970: Last Day Where You Can Still Cross
use std::collections::VecDeque;
impl Solution {
pub fn latest_day_to_cross(row: i32, col: i32, cells: Vec<Vec<i32>>) -> i32 {
let mut l: i32 = 1;
let mut r: i32 = cells.len() as i32;
let m = row as usize;
let n = col as usize;
let check = |k: i32, cells: &Vec<Vec<i32>>| -> bool {
let mut g = vec![vec![0i32; n]; m];
for i in 0..k as usize {
let x = (cells[i][0] - 1) as usize;
let y = (cells[i][1] - 1) as usize;
g[x][y] = 1;
}
let dirs = [-1, 0, 1, 0, -1];
let mut q: VecDeque<(usize, usize)> = VecDeque::new();
for j in 0..n {
if g[0][j] == 0 {
q.push_back((0, j));
g[0][j] = 1;
}
}
while let Some((x, y)) = q.pop_front() {
if x == m - 1 {
return true;
}
for i in 0..4 {
let nx = x as i32 + dirs[i];
let ny = y as i32 + dirs[i + 1];
if nx >= 0
&& nx < m as i32
&& ny >= 0
&& ny < n as i32
&& g[nx as usize][ny as usize] == 0
{
q.push_back((nx as usize, ny as usize));
g[nx as usize][ny as usize] = 1;
}
}
}
false
};
while l < r {
let mid = (l + r + 1) >> 1;
if check(mid, &cells) {
l = mid;
} else {
r = mid - 1;
}
}
l
}
}
// Accepted solution for LeetCode #1970: Last Day Where You Can Still Cross
function latestDayToCross(row: number, col: number, cells: number[][]): number {
let [l, r] = [1, cells.length];
const check = (k: number): boolean => {
const g: number[][] = Array.from({ length: row }, () => Array(col).fill(0));
for (let i = 0; i < k; ++i) {
const [x, y] = cells[i];
g[x - 1][y - 1] = 1;
}
const q: number[][] = [];
for (let j = 0; j < col; ++j) {
if (g[0][j] === 0) {
q.push([0, j]);
g[0][j] = 1;
}
}
const dirs: number[] = [-1, 0, 1, 0, -1];
for (const [x, y] of q) {
if (x === row - 1) {
return true;
}
for (let i = 0; i < 4; ++i) {
const nx = x + dirs[i];
const ny = y + dirs[i + 1];
if (nx >= 0 && nx < row && ny >= 0 && ny < col && g[nx][ny] === 0) {
q.push([nx, ny]);
g[nx][ny] = 1;
}
}
}
return false;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (check(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.