Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Valid Parenthesis String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "678" 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

Given a string s containing only three types of characters: '(', ')' and '', return true if s is valid. The following rules define a valid string: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "". Example 1: Input: s = "()" Output: true Example 2: Input: s = "()" Output: true Example 3: Input: s = "())" Output: true Constraints: 1 <= s.length <= 100 s[i] is '(', ')' or '*'.

Explanation

Here's the approach to solve this problem:

  • Maintain Range of Open Parentheses: Instead of tracking the exact count of open parentheses, maintain a range using low and high. low represents the minimum possible open parentheses count, and high represents the maximum possible open parentheses count.
  • Iterate and Update: Iterate through the string. If we encounter '(', increment both low and high. If we encounter ')', decrement both low and high. If we encounter '*', increment high and decrement low.
  • Handle Edge Cases: Ensure low never becomes negative (minimum open parentheses can't be negative). At the end, the string is valid if low is 0 (all necessary open parentheses have been closed). Also, ensure high never goes negative, since the maximum can't be negative either, and we use this upper bound to make sure we can close enough open parentheses.

  • Time and Space Complexity: O(n) time complexity, O(1) space complexity.

Code

    def checkValidString(s: str) -> bool:
    low = 0
    high = 0
    for char in s:
        if char == '(':
            low += 1
            high += 1
        elif char == ')':
            low -= 1
            high -= 1
        else:
            low -= 1
            high += 1

        if high < 0:
            return False

        low = max(low, 0)

    return low == 0

More from this blog

C

Chatmagic blog

2894 posts