#2267

Check if There Is a Valid Parentheses String Path

Hard
ArrayDynamic ProgrammingMatrixDynamic ProgrammingBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^(m+n))
O(m*n)
Space
O(m+n)
O(m*n)
💡

Intuition

Time O(m*n)Space O(m*n)

The optimal approach uses dynamic programming to track valid paths more efficiently. We maintain a 2D array to store the balance of parentheses at each cell, allowing us to avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a 2D DP array initialized to false, where dp[i][j] indicates if a valid path exists to cell (i, j).
  2. 2Step 2: Initialize dp[0][0] based on the first cell's value.
  3. 3Step 3: Iterate through the grid, updating dp[i][j] based on the values from the top (i-1, j) and left (i, j-1) cells, ensuring the balance remains valid.
solution.py13 lines
1# Full working Python code
2class Solution:
3    def hasValidPath(self, grid):
4        m, n = len(grid), len(grid[0])
5        dp = [[False] * n for _ in range(m)]
6        dp[0][0] = grid[0][0] == '('
7        for i in range(m):
8            for j in range(n):
9                if i > 0:
10                    dp[i][j] |= dp[i-1][j] and (grid[i][j] == '(' or (grid[i][j] == ')' and (i + j) % 2 == 1))
11                if j > 0:
12                    dp[i][j] |= dp[i][j-1] and (grid[i][j] == '(' or (grid[i][j] == ')' and (i + j) % 2 == 1))
13        return dp[m-1][n-1]

Complexity note: The time complexity is O(m*n) because we iterate through each cell in the grid once. The space complexity is also O(m*n) due to the DP table storing results for each cell.

  • 1A valid parentheses string requires that at no point do we have more closing parentheses than opening ones.
  • 2The balance of parentheses must return to zero at the end of the path.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.