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.
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
().AB (A concatenated with B), where A and B are valid parentheses strings.(A), where A is a valid parentheses string.You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions:
(0, 0).(m - 1, n - 1).Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
Example 1:
Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
Output: true
Explanation: The above diagram shows two possible paths that form valid parentheses strings.
The first path shown results in the valid parentheses string "()(())".
The second path shown results in the valid parentheses string "((()))".
Note that there may be other valid parentheses string paths.
Example 2:
Input: grid = [[")",")"],["(","("]]
Output: false
Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 100grid[i][j] is either '(' or ')'.Problem summary: A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions: The path starts from the upper left cell (0, 0). The path ends at the bottom-right cell (m - 1, n - 1). The path only ever moves down or right. The resulting parentheses string formed by the path is valid. Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]][[")",")"],["(","("]]check-if-there-is-a-valid-path-in-a-grid)check-if-a-parentheses-string-can-be-valid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2267: Check if There Is a Valid Parentheses String Path
class Solution {
private int m, n;
private char[][] grid;
private boolean[][][] vis;
public boolean hasValidPath(char[][] grid) {
m = grid.length;
n = grid[0].length;
if ((m + n - 1) % 2 == 1 || grid[0][0] == ')' || grid[m - 1][n - 1] == '(') {
return false;
}
this.grid = grid;
vis = new boolean[m][n][m + n];
return dfs(0, 0, 0);
}
private boolean dfs(int i, int j, int k) {
if (vis[i][j][k]) {
return false;
}
vis[i][j][k] = true;
k += grid[i][j] == '(' ? 1 : -1;
if (k < 0 || k > m - i + n - j) {
return false;
}
if (i == m - 1 && j == n - 1) {
return k == 0;
}
final int[] dirs = {1, 0, 1};
for (int d = 0; d < 2; ++d) {
int x = i + dirs[d], y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && dfs(x, y, k)) {
return true;
}
}
return false;
}
}
// Accepted solution for LeetCode #2267: Check if There Is a Valid Parentheses String Path
func hasValidPath(grid [][]byte) bool {
m, n := len(grid), len(grid[0])
if (m+n-1)%2 == 1 || grid[0][0] == ')' || grid[m-1][n-1] == '(' {
return false
}
vis := make([][][]bool, m)
for i := range vis {
vis[i] = make([][]bool, n)
for j := range vis[i] {
vis[i][j] = make([]bool, m+n)
}
}
dirs := [3]int{1, 0, 1}
var dfs func(i, j, k int) bool
dfs = func(i, j, k int) bool {
if vis[i][j][k] {
return false
}
vis[i][j][k] = true
if grid[i][j] == '(' {
k++
} else {
k--
}
if k < 0 || k > m-i+n-j {
return false
}
if i == m-1 && j == n-1 {
return k == 0
}
for d := 0; d < 2; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < m && y >= 0 && y < n && dfs(x, y, k) {
return true
}
}
return false
}
return dfs(0, 0, 0)
}
# Accepted solution for LeetCode #2267: Check if There Is a Valid Parentheses String Path
class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
@cache
def dfs(i: int, j: int, k: int) -> bool:
d = 1 if grid[i][j] == "(" else -1
k += d
if k < 0 or k > m - i + n - j:
return False
if i == m - 1 and j == n - 1:
return k == 0
for a, b in pairwise((0, 1, 0)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and dfs(x, y, k):
return True
return False
m, n = len(grid), len(grid[0])
if (m + n - 1) % 2 or grid[0][0] == ")" or grid[m - 1][n - 1] == "(":
return False
return dfs(0, 0, 0)
// Accepted solution for LeetCode #2267: Check if There Is a Valid Parentheses String Path
/**
* [2267] Check if There Is a Valid Parentheses String Path
*
* A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
*
* It is ().
* It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.
* It can be written as (A), where A is a valid parentheses string.
*
* You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions:
*
* The path starts from the upper left cell (0, 0).
* The path ends at the bottom-right cell (m - 1, n - 1).
* The path only ever moves down or right.
* The resulting parentheses string formed by the path is valid.
*
* Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" style="width: 521px; height: 300px;" />
* Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
* Output: true
* Explanation: The above diagram shows two possible paths that form valid parentheses strings.
* The first path shown results in the valid parentheses string "()(())".
* The second path shown results in the valid parentheses string "((()))".
* Note that there may be other valid parentheses string paths.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" style="width: 165px; height: 165px;" />
* Input: grid = [[")",")"],["(","("]]
* Output: false
* Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.
*
*
* Constraints:
*
* m == grid.length
* n == grid[i].length
* 1 <= m, n <= 100
* grid[i][j] is either '(' or ')'.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/
// discuss: https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn has_valid_path(grid: Vec<Vec<char>>) -> bool {
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2267_example_1() {
let grid = vec![
vec!['(', '(', '('],
vec![')', '(', ')'],
vec!['(', '(', ')'],
vec!['(', '(', ')'],
];
let result = true;
assert_eq!(Solution::has_valid_path(grid), result);
}
#[test]
#[ignore]
fn test_2267_example_2() {
let grid = vec![vec![')', ')'], vec!['(', '(']];
let result = false;
assert_eq!(Solution::has_valid_path(grid), result);
}
}
// Accepted solution for LeetCode #2267: Check if There Is a Valid Parentheses String Path
function hasValidPath(grid: string[][]): boolean {
const m = grid.length,
n = grid[0].length;
if ((m + n - 1) % 2 || grid[0][0] === ')' || grid[m - 1][n - 1] === '(') {
return false;
}
const vis: boolean[][][] = Array.from({ length: m }, () =>
Array.from({ length: n }, () => Array(m + n).fill(false)),
);
const dirs = [1, 0, 1];
const dfs = (i: number, j: number, k: number): boolean => {
if (vis[i][j][k]) {
return false;
}
vis[i][j][k] = true;
k += grid[i][j] === '(' ? 1 : -1;
if (k < 0 || k > m - i + n - j) {
return false;
}
if (i === m - 1 && j === n - 1) {
return k === 0;
}
for (let d = 0; d < 2; ++d) {
const x = i + dirs[d],
y = j + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && dfs(x, y, k)) {
return true;
}
}
return false;
};
return dfs(0, 0, 0);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
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: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.