LeetCode #678 Medium

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.

Constraints
  • 1 <= s.length <= 100
  • s[i] is '(', ')' or '*'.
greedystringsstack
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def checkValidString(self, s):
▶3 low = high = 0
▶4 for ch in s:
▶5 if ch == "(":
▶6 low += 1
▶7 high += 1
▶8 elif ch == ")":
▶9 low -= 1
▶10 high -= 1
▶11 else:
▶12 low -= 1
▶13 high += 1
▶14 if high < 0:
▶15 return False
▶16 low = max(low, 0)
▶17 return low == 0
(0*1)2)3open brackets that are still possible−10low, high12nothing read → 0 open
low0
high0
Before any character, exactly 0 brackets are open, so the range is just 0. low will track the fewest open brackets any choice of stars can give, and high the most.
(0read*1)2)3open brackets that are still possible−101low, high2'(' opens one → 1 open
low1
high1
An opening bracket adds one open bracket under every choice, so both ends move up by 1: now 1.
(0*1read)2)3open brackets that are still possible−10low12high'*' could close, vanish or open → range widens
low0
high2
A star can close a bracket (count − 1), be empty (count unchanged) or open one (count + 1). So low moves down and high moves up, covering all three at once. The range is now 0 to 2.
(0*1)2read)3open brackets that are still possible−1low01high2')' closes one → low drops to −1
low-1
high1
A closing bracket closes one under every choice, so both ends move down by 1: low is -1 and high is 1. A count of −1 is impossible; that is fixed next.
(0*1)2read)3open brackets that are still possible−10low1high2−1 open is impossible → low back to 0
low0
high1
A count of −1 only comes from choices that have closed more brackets than they opened, and those choices are impossible. Dropping them raises the fewest open to 0: in the choices that remain, a star that would have closed counts as empty instead. The range is now 0 to 1.
(0*1)2)3readopen brackets that are still possible−1low0high12')' closes one → low drops to −1
low-1
high0
A closing bracket closes one under every choice, so both ends move down by 1: low is -1 and high is 0. A count of −1 is impossible; that is fixed next.
(0*1)2)3readopen brackets that are still possible−10low, high12−1 open is impossible → low back to 0
low0
high0
A count of −1 only comes from choices that have closed more brackets than they opened, and those choices are impossible. Dropping them raises the fewest open to 0: in the choices that remain, a star that would have closed counts as empty instead. The range is now 0.
(0*1)2)3open brackets that are still possible−10low, high120 is in the range → valid
low0
high0
Every character is read and the range still includes 0: some choice of stars closes every bracket. Return true.
05

Common pitfalls

Letting low go below zero

✗ Wrong
if high < 0:
    return False
# no clamp
✓ Right
if 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

✗ Wrong
if low < 0:
    return False
✓ Right
if high < 0:
    return False

On "*)", 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

✗ Wrong
opens, closes, stars = s.count("("), s.count(")"), s.count("*")
return abs(opens - closes) <= stars
✓ Right
Scan 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.

06

Edge cases

Only stars

Every star can be empty. low is raised back to 0 after each one, so the answer is true.

The string starts with )

high is −1 after the first character, so the answer is false before the rest is read.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the string with constant work per character. Only the two counters low and high are stored.
08

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.