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 grid. Each cell of grid represents a street. The street of grid[i][j] can be:
1 which means a street connecting the left cell and the right cell.2 which means a street connecting the upper cell and the lower cell.3 which means a street connecting the left cell and the lower cell.4 which means a street connecting the right cell and the lower cell.5 which means a street connecting the left cell and the upper cell.6 which means a street connecting the right cell and the upper cell.You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.
Notice that you are not allowed to change any street.
Return true if there is a valid path in the grid or false otherwise.
Example 1:
Input: grid = [[2,4,3],[6,5,2]] Output: true Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
Example 2:
Input: grid = [[1,2,1],[1,2,1]] Output: false Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
Example 3:
Input: grid = [[1,1,2]] Output: false Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 3001 <= grid[i][j] <= 6Problem summary: You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be: 1 which means a street connecting the left cell and the right cell. 2 which means a street connecting the upper cell and the lower cell. 3 which means a street connecting the left cell and the lower cell. 4 which means a street connecting the right cell and the lower cell. 5 which means a street connecting the left cell and the upper cell. 6 which means a street connecting the right cell and the upper cell. You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets. Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Union-Find
[[2,4,3],[6,5,2]]
[[1,2,1],[1,2,1]]
[[1,1,2]]
check-if-there-is-a-valid-parentheses-string-path)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
class Solution {
private int[] p;
private int[][] grid;
private int m;
private int n;
public boolean hasValidPath(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
p = new int[m * n];
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int e = grid[i][j];
if (e == 1) {
left(i, j);
right(i, j);
} else if (e == 2) {
up(i, j);
down(i, j);
} else if (e == 3) {
left(i, j);
down(i, j);
} else if (e == 4) {
right(i, j);
down(i, j);
} else if (e == 5) {
left(i, j);
up(i, j);
} else {
right(i, j);
up(i, j);
}
}
}
return find(0) == find(m * n - 1);
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private void left(int i, int j) {
if (j > 0 && (grid[i][j - 1] == 1 || grid[i][j - 1] == 4 || grid[i][j - 1] == 6)) {
p[find(i * n + j)] = find(i * n + j - 1);
}
}
private void right(int i, int j) {
if (j < n - 1 && (grid[i][j + 1] == 1 || grid[i][j + 1] == 3 || grid[i][j + 1] == 5)) {
p[find(i * n + j)] = find(i * n + j + 1);
}
}
private void up(int i, int j) {
if (i > 0 && (grid[i - 1][j] == 2 || grid[i - 1][j] == 3 || grid[i - 1][j] == 4)) {
p[find(i * n + j)] = find((i - 1) * n + j);
}
}
private void down(int i, int j) {
if (i < m - 1 && (grid[i + 1][j] == 2 || grid[i + 1][j] == 5 || grid[i + 1][j] == 6)) {
p[find(i * n + j)] = find((i + 1) * n + j);
}
}
}
// Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
func hasValidPath(grid [][]int) bool {
m, n := len(grid), len(grid[0])
p := make([]int, m*n)
for i := range p {
p[i] = i
}
var find func(x int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
left := func(i, j int) {
if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) {
p[find(i*n+j)] = find(i*n + j - 1)
}
}
right := func(i, j int) {
if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) {
p[find(i*n+j)] = find(i*n + j + 1)
}
}
up := func(i, j int) {
if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) {
p[find(i*n+j)] = find((i-1)*n + j)
}
}
down := func(i, j int) {
if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) {
p[find(i*n+j)] = find((i+1)*n + j)
}
}
for i, row := range grid {
for j, e := range row {
if e == 1 {
left(i, j)
right(i, j)
} else if e == 2 {
up(i, j)
down(i, j)
} else if e == 3 {
left(i, j)
down(i, j)
} else if e == 4 {
right(i, j)
down(i, j)
} else if e == 5 {
left(i, j)
up(i, j)
} else {
right(i, j)
up(i, j)
}
}
}
return find(0) == find(m*n-1)
}
# Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
p = list(range(m * n))
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def left(i, j):
if j > 0 and grid[i][j - 1] in (1, 4, 6):
p[find(i * n + j)] = find(i * n + j - 1)
def right(i, j):
if j < n - 1 and grid[i][j + 1] in (1, 3, 5):
p[find(i * n + j)] = find(i * n + j + 1)
def up(i, j):
if i > 0 and grid[i - 1][j] in (2, 3, 4):
p[find(i * n + j)] = find((i - 1) * n + j)
def down(i, j):
if i < m - 1 and grid[i + 1][j] in (2, 5, 6):
p[find(i * n + j)] = find((i + 1) * n + j)
for i in range(m):
for j in range(n):
e = grid[i][j]
if e == 1:
left(i, j)
right(i, j)
elif e == 2:
up(i, j)
down(i, j)
elif e == 3:
left(i, j)
down(i, j)
elif e == 4:
right(i, j)
down(i, j)
elif e == 5:
left(i, j)
up(i, j)
else:
right(i, j)
up(i, j)
return find(0) == find(m * n - 1)
// Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
struct Solution;
use std::collections::VecDeque;
trait Connect {
fn top(self) -> bool;
fn left(self) -> bool;
fn bottom(self) -> bool;
fn right(self) -> bool;
}
impl Connect for i32 {
fn top(self) -> bool {
matches!(self, 2 | 5 | 6)
}
fn left(self) -> bool {
matches!(self, 1 | 3 | 5)
}
fn bottom(self) -> bool {
matches!(self, 2 | 3 | 4)
}
fn right(self) -> bool {
matches!(self, 1 | 4 | 6)
}
}
impl Solution {
fn has_valid_path(grid: Vec<Vec<i32>>) -> bool {
let n = grid.len();
let m = grid[0].len();
let mut visited = vec![vec![false; m]; n];
let mut queue: VecDeque<(usize, usize)> = VecDeque::new();
queue.push_back((0, 0));
while let Some((i, j)) = queue.pop_front() {
visited[i][j] = true;
if visited[n - 1][m - 1] {
return true;
}
if i > 0 && !visited[i - 1][j] && grid[i][j].top() && grid[i - 1][j].bottom() {
queue.push_back((i - 1, j));
}
if j > 0 && !visited[i][j - 1] && grid[i][j].left() && grid[i][j - 1].right() {
queue.push_back((i, j - 1));
}
if i + 1 < n && !visited[i + 1][j] && grid[i][j].bottom() && grid[i + 1][j].top() {
queue.push_back((i + 1, j));
}
if j + 1 < m && !visited[i][j + 1] && grid[i][j].right() && grid[i][j + 1].left() {
queue.push_back((i, j + 1));
}
}
false
}
}
#[test]
fn test() {
let grid = vec_vec_i32![[2, 4, 3], [6, 5, 2]];
let res = true;
assert_eq!(Solution::has_valid_path(grid), res);
let grid = vec_vec_i32![[1, 2, 1], [1, 2, 1]];
let res = false;
assert_eq!(Solution::has_valid_path(grid), res);
let grid = vec_vec_i32![[1, 1, 2]];
let res = false;
assert_eq!(Solution::has_valid_path(grid), res);
let grid = vec_vec_i32![[1, 1, 1, 1, 1, 1, 3]];
let res = true;
assert_eq!(Solution::has_valid_path(grid), res);
let grid = vec_vec_i32![[2], [2], [2], [2], [2], [2], [6]];
let res = true;
assert_eq!(Solution::has_valid_path(grid), res);
}
// Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1391: Check if There is a Valid Path in a Grid
// class Solution {
// private int[] p;
// private int[][] grid;
// private int m;
// private int n;
//
// public boolean hasValidPath(int[][] grid) {
// this.grid = grid;
// m = grid.length;
// n = grid[0].length;
// p = new int[m * n];
// for (int i = 0; i < p.length; ++i) {
// p[i] = i;
// }
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// int e = grid[i][j];
// if (e == 1) {
// left(i, j);
// right(i, j);
// } else if (e == 2) {
// up(i, j);
// down(i, j);
// } else if (e == 3) {
// left(i, j);
// down(i, j);
// } else if (e == 4) {
// right(i, j);
// down(i, j);
// } else if (e == 5) {
// left(i, j);
// up(i, j);
// } else {
// right(i, j);
// up(i, j);
// }
// }
// }
// return find(0) == find(m * n - 1);
// }
//
// private int find(int x) {
// if (p[x] != x) {
// p[x] = find(p[x]);
// }
// return p[x];
// }
//
// private void left(int i, int j) {
// if (j > 0 && (grid[i][j - 1] == 1 || grid[i][j - 1] == 4 || grid[i][j - 1] == 6)) {
// p[find(i * n + j)] = find(i * n + j - 1);
// }
// }
//
// private void right(int i, int j) {
// if (j < n - 1 && (grid[i][j + 1] == 1 || grid[i][j + 1] == 3 || grid[i][j + 1] == 5)) {
// p[find(i * n + j)] = find(i * n + j + 1);
// }
// }
//
// private void up(int i, int j) {
// if (i > 0 && (grid[i - 1][j] == 2 || grid[i - 1][j] == 3 || grid[i - 1][j] == 4)) {
// p[find(i * n + j)] = find((i - 1) * n + j);
// }
// }
//
// private void down(int i, int j) {
// if (i < m - 1 && (grid[i + 1][j] == 2 || grid[i + 1][j] == 5 || grid[i + 1][j] == 6)) {
// p[find(i * n + j)] = find((i + 1) * n + j);
// }
// }
// }
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.