2267. Check if There Is a Valid Parentheses String Path

2 min read

LeetCode Daily Problem: Check if There Is a Valid Parentheses String Path

On this page

Original problem on LeetCode

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.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • grid[i][j] is either '(' or ')'.

Approach 1: BFS

The question is whether a path exists, so the moment we find one we can return true. To discard invalid paths while moving, I used BFS. In the worst case, after at most m + n - 1 rounds we will have traversed the grid from start to finish.

python
class Solution:
    def hasValidPath(self, grid: list[list[str]]) -> bool:
        m, n = len(grid), len(grid[0])
        length = m+n-1
        if length % 2 == 1 or grid[0][0] == ')' or grid[-1][-1] == '(':
            return False # the start and end cells are unavoidable; the length must also be even
        
        q = deque([(0,0,0,0)]) # row, col, open count, close count
        while q:
            q = deque(set(q)) # a sneaky way to deduplicate
            size = len(q)
            for _ in range(size):
                row, col, left, right = q.popleft()
                if row >= m or col >= n or right > left or left > length // 2:
                    continue

                if grid[row][col] == '(':
                    q.append((row+1, col, left+1, right))
                    q.append((row, col+1, left+1, right))
                else:
                    if row == m-1 and col == n-1 and left-right == 1:
                        return True

                    q.append((row+1, col, left, right+1))
                    q.append((row, col+1, left, right+1))
        return False

Complexity

The BFS explores reachable (row, col, balance) states. The queue and the deduplication set are bounded by the number of such states, which is O(m * n * (m + n)) in the worst case.

TagsBFSStack

Back to all posts