Leetcode #2267: Check if There Is a Valid Parentheses String Path
In this guide, we solve Leetcode #2267 ** Check if There Is a Valid Parentheses String Path** in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 ().
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Dynamic Programming, Matrix
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
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)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.