Problem Description
Given an m x n grid containing only '(' and ')', determine if there exists a path from the top-left to the bottom-right cell (only moving down or right) such that the concatenated characters form a valid parentheses string. A valid parentheses string never has more ')' than '(' at any point, and must finally balance to zero.
Key Insights
- Use dynamic programming (DP) to track feasible "balance" states (number of unmatched '(') along each cell.
- Transition: moving right or down updates the balance (+1 for '(' and -1 for ')'). Discard states that become negative as they represent invalid sequences.
- At the bottom-right cell, a valid path must yield a balance of zero.
- The number of states can be pruned by only tracking valid, non-negative balances.
Space and Time Complexity
Time Complexity: O(m * n * k) where k is limited by the maximum balance (which is O(m+n) in the worst case). Space Complexity: O(m * n * k) for storing the set of possible balances at each grid cell.
Solution
We solve the problem using a dynamic programming approach where each cell [i][j] stores a set of possible balance values derived from all valid paths reaching that cell. Starting from the top-left, update the balance as you move right or down. If at any point the calculated balance is negative, that state is discarded. At the end, if the set at the bottom-right cell contains zero, then there exists a valid path.