Problem Description
You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path that starts from the upper left cell (0, 0), ends at the bottom-right cell (m - 1, n - 1), only moves down or right, and forms a valid parentheses string. Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.
Key Insights
- A valid parentheses string can be constructed only if the number of opening parentheses '(' is greater than or equal to the number of closing parentheses ')' at any point in the path.
- The path can only move in two directions: down or right.
- A dynamic programming (DP) approach can be employed to keep track of the valid paths based on the current balance of parentheses.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n)
Solution
The solution involves using a dynamic programming approach to keep track of the valid parentheses balance at each cell in the grid. We can use a 2D boolean array dp
where dp[i][j]
indicates if there is a valid parentheses string path from the start to cell (i, j). Additionally, we maintain the balance of parentheses as we traverse the grid. The balance is incremented by 1 for each '(' and decremented by 1 for each ')'. A valid path exists if the balance is non-negative at each step and ends at a balance of zero at the bottom-right cell.