This "Hard" problem asks if there is a path from the top-left to the bottom-right of a matrix filled with '(' and ')' that forms a valid parentheses string. A valid string must have an equal number of opening and closing parentheses, and at no point should the number of closing parentheses exceed the number of opening ones.
Google uses this to test advanced Dynamic Programming and state-space reduction. It combines the rules of valid parentheses (stack-like behavior) with grid traversal. It evaluates your ability to prune impossible paths early (e.g., if the balance becomes negative or too high to ever return to zero).
The pattern is Dynamic Programming with State Pruning. The state at each cell is the current "balance" (count of '(' minus count of ')'). dp[i][j][balance] is a boolean indicating if a balance of balance is reachable at cell . Similar to the previous problem, the path length is , which must be even. Also, the start must be '(' and the end must be ')'.
Matrix: ( ( ) ( ) ( ) ) )
Candidates often forget the "never go negative" rule, which is the defining characteristic of valid parentheses. Another mistake is not recognizing that the maximum possible balance is limited by the remaining path length, allowing for significant state-space optimization. Some might try to use a stack in DFS, which leads to redundant work.
Valid parentheses problems are almost always about "balance." If you can represent the state as a single integer (balance), you can often turn a complex string problem into a simple DP or reachability problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Fertile Pyramids in a Land | Hard | Solve | |
| Paths in Matrix Whose Sum Is Divisible by K | Hard | Solve | |
| Maximum Vacation Days | Hard | Solve | |
| Minimum Falling Path Sum II | Hard | Solve | |
| Cherry Pickup II | Hard | Solve |