Valid Parenthesis String

Medium

Topics
StringGreedyDynamic ProgrammingStack

Given a string s containing only (, ) and *, return true if it can be made a valid parentheses string. A * can be treated as (, ), or an empty string.

Example 1

(0)1
Each * can be an opener, a closer, or nothing, so a single counter cannot represent the state. Tracking the range of possible open counts does: a * widens it both ways, the high end going negative is fatal, and the low end is clamped at zero. Valid when the range still includes 0 at the end — here true.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "()"
Output: true

Example 2

(0*1)2
wildcard — ( or ) or nothing
Input:  s = "(*)"
Output: true

Example 3

(0*1)2)3
wildcard — ( or ) or nothing
Input:  s = "(*))"
Output: true

Constraints

  • 1 <= s.length <= 100
  • s consists of '(', ')' and '*'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Instead of committing each *, track the range of possible open-paren counts. lo is the fewest opens still unmatched (treat * as )), hi is the most (treat * as (). The string is valid if 0 stays achievable.

Approach

  1. For "(" increment both lo and hi; for ")" decrement both; for "*" decrement lo and increment hi.
  2. Clamp lo at 0 (open count can never go negative).
  3. If hi ever goes negative there are too many ")"; fail. At the end lo must be 0.

Dry Run

s = "(*)".  Track a RANGE of possible open-bracket counts rather than one number,
since each '*' can be '(', ')' or nothing.
  '('   lo 1   hi 1
  '*'   lo 0   hi 2     -- lo assumes ')', hi assumes '('
  ')'   lo 0   hi 1     -- lo would be -1 and is clamped back to 0
answer lo == 0, so true
and on "(((((*":
  five '(' take both to 5, then '*' gives lo 4, hi 6
  the string ends with lo = 4, not 0  ->  false
hi is the optimistic count and lo the pessimistic one. The string is valid exactly
when 0 stays inside [lo, hi] throughout and lo returns to 0 at the end -- there is
some assignment of the stars making the count balance.
The clamp on lo is load-bearing, and the first example shows why. At the '*', lo
drops to 0 by assuming ')'. At the ')' it would go to -1, which would mean "more
closers than openers" -- but a count can never be negative; the real meaning is
that the '*' simply should not have been a ')'. Clamping encodes that. Without it,
"(*)" returns false, and so does "*)".
hi going negative is different and is a real failure: it means even the most
generous reading has more closers than openers, so the function returns
immediately.

Complexity

  • Time — O(n): a single pass maintaining two counters.
  • Space — O(1): constant extra space.

Common Pitfalls

  • Clamp lo to 0 each step, otherwise extra "*" treated as ")" push it artificially negative.

Full Solution — all languages

class Solution:
    def checkValidString(self, s):
        lo=hi=0
        for c in s:
            if c=='(':
                lo+=1; hi+=1
            elif c==')':
                lo-=1; hi-=1
            else:
                lo-=1; hi+=1
            if hi<0: return False
            lo=max(lo,0)
        return lo==0
SensAI
Beta
Tap the mic to stop voice mode