Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check if There Is a Valid Parentheses String Path

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2267" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 ')'.

Explanation

Here's a breakdown of the solution and the Python code:

  • Key Idea: Use Dynamic Programming to track the possible balance values (number of open parentheses minus the number of closed parentheses) at each cell. A path is valid if it reaches the bottom-right cell with a balance of 0.
  • Optimization: The balance value can range from -1 to m + n. Prune paths early if the balance becomes negative, as it can never lead to a valid string.
  • DP State: dp[i][j][k] is True if it's possible to reach cell (i, j) with a balance of k, and False otherwise.

  • Complexity: Time: O(m n (m + n)), Space: O(m n (m + n))

Code

    def hasValidPath(grid):
    m, n = len(grid), len(grid[0])

    # If the total path length is odd, it cannot be a valid parentheses string
    if (m + n - 1) % 2 != 0:
        return False

    dp = {}  # Use a dictionary for sparse storage

    def solve(row, col, balance):
        if row == m or col == n or balance < 0:
            return False

        balance += 1 if grid[row][col] == '(' else -1

        if row == m - 1 and col == n - 1:
            return balance == 0

        if (row, col, balance) in dp:
            return dp[(row, col, balance)]

        dp[(row, col, balance)] = solve(row + 1, col, balance) or solve(row, col + 1, balance)
        return dp[(row, col, balance)]

    return solve(0, 0, 0)

More from this blog

C

Chatmagic blog

2894 posts