Skip to content

2267. Check if There Is a Valid Parentheses String Path

Description

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.

 

Example 1:

Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]
Output: true
Explanation: The above diagram shows two possible paths that form valid parentheses strings.
The first path shown results in the valid parentheses string "()(())".
The second path shown results in the valid parentheses string "((()))".
Note that there may be other valid parentheses string paths.

Example 2:

Input: grid = [[")",")"],["(","("]]
Output: false
Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.

 

Constraints:

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

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(mn*(m+n))
  • Space complexity: O(mn*(m+n))

 

JavaScript

js
/**
 * @param {character[][]} grid
 * @return {boolean}
 */
const hasValidPath = function (grid) {
  const m = grid.length;
  const n = grid[0].length;
  const dp = Array.from({ length: m }, () => {
    return new Array(n)
      .fill('')
      .map(() => new Array(m + n).fill(-1));
  });

  const findValidPath = (row, col, parentheses) => {
    if (row >= m || col >= n) return false;
    if (dp[row][col][parentheses] !== -1) return dp[row][col][parentheses];

    const value = grid[row][col];
    const diff = value === '(' ? 1 : -1;
    const nextParentheses = parentheses + diff;

    if (nextParentheses < 0) return false;
    if (nextParentheses > m + n - row - col) return false;
    if (row === m - 1 && col === n - 1) {
      return nextParentheses === 0;
    }

    const down = findValidPath(row + 1, col, nextParentheses);
    const right = findValidPath(row, col + 1, nextParentheses);
    const result = down || right;

    dp[row][col][parentheses] = result;

    return result;
  };

  return findValidPath(0, 0, 0);
};

Released under the MIT license