Python 0678.py
class Solution:
def checkValidString(self, s: str) -> bool:
@cache
def deeper(pos, depth):
# mismatch
if depth < 0:
return False
# end of input
if pos == len(s):
return depth == 0
c = s[pos]
if c == "(":
return deeper(pos + 1, depth + 1)
if c == ")":
return deeper(pos + 1, depth - 1)
# must be "*", try to replace it by "", "(" or ")"
return deeper(pos + 1, depth) or \
deeper(pos + 1, depth + 1) or \
deeper(pos + 1, depth - 1)
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 40% (1+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Greedy
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method checkValidString. The method determines whether a given string s, composed of the characters '(', ')', and '*', can be interpreted as a valid parenthesis sequence. The core of the algorithm is a depth-first search that explores all possible interpretations of each '*' character while tracking the current nesting depth of parentheses. Memoization is employed to avoid recomputing identical sub-problems, which makes the exhaustive search tractable for typical input sizes.
Key Steps
The algorithm introduces an inner recursive function named deeper. This helper receives two arguments: pos, the current index in the input string, and depth, the net count of unmatched opening parentheses encountered so far.
@cache
def deeper(pos, depth):
The first conditional checks for an impossible state where the nesting depth has become negative. A negative depth indicates that more closing parentheses have been processed than opening ones, which cannot lead to a valid configuration. In this case the function returns False immediately, pruning the search branch.
if depth < 0:
return False
The second conditional detects the termination condition when the end of the string is reached. At this point the string is valid only if the nesting depth has been reduced back to zero, meaning every opening parenthesis has been matched.
if pos == len(s):
return depth == 0
The character at the current position is examined next. If it is an opening parenthesis '(', the recursion proceeds to the next character while incrementing the depth, reflecting the addition of an unmatched opening parenthesis.
c = s[pos]
if c == "(":
return deeper(pos + 1, depth + 1)
If the character is a closing parenthesis ')', the depth is decremented before the recursive call, representing the consumption of a previously unmatched opening parenthesis.
if c == ")":
return deeper(pos + 1, depth - 1)
When the character is a wildcard '*', the function explores three distinct possibilities: treating the star as an empty string (no change to depth), as an opening parenthesis (increment depth), or as a closing parenthesis (decrement depth). The logical OR combines the results, returning True if any of the three branches yields a valid configuration.
return deeper(pos + 1, depth) or \
deeper(pos + 1, depth + 1) or \
deeper(pos + 1, depth - 1)
Finally, the public method initiates the recursion from the start of the string with a neutral depth of zero.
return deeper(0, 0)
Edge Cases Handled
The implementation explicitly guards against a depth that drops below zero, which captures scenarios where a closing parenthesis appears before any matching opening parenthesis. This early exit prevents unnecessary exploration of paths that cannot succeed.
When the input string is empty, the termination condition pos == len(s) is satisfied immediately, and the function returns True because the initial depth is zero, correctly treating the empty string as a valid sequence.
The wildcard handling accounts for the three semantic interpretations of '*'. By trying each alternative, the algorithm correctly validates strings where stars must be interpreted differently in different positions to achieve balance.
If the string ends with a non-zero depth, the termination check ensures that the function returns False, covering cases where there are unmatched opening parentheses left at the end of the input.
Performance Optimizations
The most significant optimization is the use of the @cache decorator (from functools). This memoization caches the result of each (pos, depth) pair, guaranteeing that each unique sub-problem is evaluated at most once. Since the recursion can otherwise revisit the same state many times-especially when multiple stars generate overlapping branches-the cache dramatically reduces the number of recursive calls.
The early rejection of negative depth states also contributes to efficiency. By halting recursion as soon as an impossible configuration is detected, the algorithm avoids descending deeper into branches that would inevitably fail.
Because the recursion depth never exceeds the length of the input string, the call stack remains bounded, and the memoization table size is limited to the product of the string length and the range of feasible depths, which is inherently constrained by the same length. This containment prevents uncontrolled memory growth while still enabling exhaustive exploration of all viable interpretations.
ELI5 - Simplified Explanation
Imagine reading a story that uses magic symbols to represent opening and closing parentheses. Some of the symbols are stars that can turn into whatever is needed to keep the story balanced. The code walks through the string one piece at a time, keeping track of how many open parentheses are currently waiting to be matched.
Think of depth as holding balloons. An opening symbol means grabbing a new balloon, and a closing symbol means letting one go. If the count of balloons ever drops below zero, the sequence has failed because there is no balloon left to hold. If the code reaches the very end of the string and holds exactly zero balloons, everything is perfect.
When the code encounters a star, it feels like a branching path in a game. Because stars are flexible, the code tries all three possibilities. It checks what happens if the star disappears, what happens if it acts like an opening symbol, and what happens if it acts like a closing symbol. By looking at all these paths, the code discovers if there is at least one way to make the entire string match up correctly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 761: Special Binary String
Solved On The Same Day
- problem 2401: Longest Nice Subarray
- problem 2419: Longest Subarray With Maximum Bitwise AND
- problem 2438: Range Product Queries of Powers
- problem 2439: Minimize Maximum of Array
- problem 2447: Number of Subarrays With GCD Equal to K
- problem 2452: Words Within Two Edits of Dictionary
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality