Valid Parenthesis String
Valid Parenthesis String is LeetCode 678 (Medium). Given a string s made of (, ) and *, return true if it can be a valid bracket string. Each * may stand for (, for ), or for nothing.
- Every
(must be closed by a)somewhere after it. - Every
)must close a(somewhere before it.
The string has at most 100 characters, so an O(n²) table would pass, but trying all three meanings of every * (3ⁿ cases) would not.
- 1 <= s.length <= 100
- s[i] is '(', ')' or '*'.
Intuition
Count the ( still waiting to be closed as you read. Each * makes that count uncertain. Instead of branching, keep the range of open brackets still possible:
low: the fewest open, if stars close brackets whenever they can.high: the most open, if every star opens one.
( raises both ends, ) lowers both, and * lowers low while raising high. Every count in between is also possible, because changing one star's meaning moves the count by one.
If high falls below 0, some ) has nothing to close under every choice. At the end, the string is valid exactly when 0 is in the range, that is, when low is 0.
Wildcards that can play several roles turn the single open-bracket counter of the plain problem into a range. Track its lowest and highest possible value instead of trying every assignment.
Approach
Before reading on, work out the fewest and the most unclosed ( after reading (*. Then decide what a negative fewest count means, and what you should do about it. Aim for O(n) time and O(1) space.
Start with an empty range
Set low = high = 0. Before any character is read, the only possible number of unclosed ( is 0, so the range holds just that one value.
Move the range for each character
( adds 1 to both low and high, and ) subtracts 1 from both. * subtracts 1 from low and adds 1 to high, so its three meanings (close one, nothing, open one) are all covered at once.
Fail as soon as high is negative
If high < 0, return false at once. Even with every star used as (, more brackets have been closed than opened, and characters read later cannot reach back to fix an earlier ).
Raise low back to zero
If low drops below 0, set it to 0. A negative count only comes from choices where a star closed a bracket that did not exist. Those choices are impossible, so they are dropped, and that star is treated as empty instead.
Check low at the end
After the last character, return low == 0. If even the choice with the fewest open brackets leaves some ( unclosed, no choice of stars can close them all.
Code in Python, C++ and Java
Common pitfalls
Letting low go below zero
if high < 0:
return False
# no clampif high < 0:
return False
low = max(low, 0)On "(*)", low goes 1, 0, then −1 at the ). Without the clamp it ends at −1, the final low == 0 test fails, and a valid string is rejected. The −1 described the star closing the (, leaving nothing for the ) to close, and that choice was never possible.
Failing when low goes negative
if low < 0:
return Falseif high < 0:
return FalseOn "*)", low is −1 after the star, so this code returns false. But the star can be (, giving (). A negative low only rules out some choices; the string is broken only when high, the most generous choice, goes negative.
Comparing totals and ignoring order
opens, closes, stars = s.count("("), s.count(")"), s.count("*")
return abs(opens - closes) <= starsScan left to right, tracking low and high.
A star can only close a ( that comes before it. On "*(" the totals look fine, one ( and one star, but the star is in front of the (, so nothing can close it and the answer is false.
Edge cases
Every star can be empty. low is raised back to 0 after each one, so the answer is true.
)high is −1 after the first character, so the answer is false before the rest is read.
Complexity
low and high are stored.Valid Parenthesis String FAQ
Why does the stack from Valid Parentheses not work here?
A plain stack decides each ) against the last (, but a * cannot be classed when it is read. The stack version keeps two stacks of indices, one for ( and one for *. A ) pops a ( if there is one, else a *. At the end, each leftover ( needs a leftover * at a later index. That is O(n) time but O(n) space.
Why is every count between low and high possible?
Start from the choice where every star is (, which gives high. Change one star at a time, from ( to nothing or from nothing to ): each change lowers the count by exactly 1 from that point on. Walking down this way passes through every value until the fewest-open choice, so checking only the two ends is enough.
Is there a dynamic programming solution?
Yes. Let dp[i][c] be whether the first i characters can leave exactly c brackets open. ( moves c up by one, ) moves it down, a star may do either or leave it alone, c may never go below 0, and the answer is dp[n][0]. It is O(n²) time, fine for 100 characters, and the low/high pair is this table compressed to its two ends.