Check if There Is a Valid Parentheses String Path - Problem
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.
Input & Output
Example 1 — Valid Path Exists
$
Input:
grid = [["(",")"],["(",")"]]
›
Output:
true
💡 Note:
Path (0,0)→(0,1)→(1,1) gives string "())" which is invalid, but path (0,0)→(1,0)→(1,1) gives string "(()" which is also invalid. However, we need to find "()". Path (0,0)→(0,1) gives "()" which is valid.
Example 2 — No Valid Path
$
Input:
grid = [[")","("],["(",")"]]
›
Output:
false
💡 Note:
All paths start with ")" which immediately makes the balance negative, so no valid parentheses string can be formed.
Example 3 — Larger Grid
$
Input:
grid = [["(","(",")"],[")",")","("],["(",")",")"]]
›
Output:
true
💡 Note:
There exists at least one path that forms a valid parentheses string by carefully choosing down/right moves.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- grid[i][j] is either '(' or ')'
Visualization
Tap to expand
Understanding the Visualization
1
Grid Input
2D matrix of '(' and ')' characters
2
Path Constraint
Can only move right or down
3
Valid Check
Path string must be valid parentheses
Key Takeaway
🎯 Key Insight: Track parentheses balance at each position and ensure it never becomes negative while reaching the destination.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code