Solving Leetcode Interviews in Seconds with AI: Valid Parenthesis String
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
lowandhigh.lowrepresents the minimum possible open parentheses count, andhighrepresents the maximum possible open parentheses count. - Iterate and Update: Iterate through the string. If we encounter '(', increment both
lowandhigh. If we encounter ')', decrement bothlowandhigh. If we encounter '*', incrementhighand decrementlow. Handle Edge Cases: Ensure
lownever becomes negative (minimum open parentheses can't be negative). At the end, the string is valid iflowis 0 (all necessary open parentheses have been closed). Also, ensurehighnever 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