sagelearnai

Valid Parenthesis String

Difficulty: Medium · Pattern: Greedy · LeetCode #678

s contains '(', ')' and '*', where '*' can be '(', ')' or empty. Return true if some choice of the '*'s makes s a valid parentheses string.

Examples

text
"()"     →  true
"(*)"    →  true
"(*))"   →  true
"((*"    →  false   (one star cannot close two opens)

Hints

  1. With no stars you'd track a single open-count. With stars, the count could be any of a range of values.
  2. Track lo (fewest possible open parens) and hi (most possible).

Approach

Scan left to right while maintaining [lo, hi], the range of possible unmatched ( counts:

  • ( → lo += 1, hi += 1
  • ) → lo -= 1, hi -= 1
  • * → lo -= 1 (treat it as )), hi += 1 (treat it as ()
  • If hi < 0, there are too many ) no matter what, so return false.
  • Clamp lo = max(lo, 0), because we can never have negative open parens, so those choices are discarded.

At the end, valid ⟺ lo == 0, meaning some choice balances everything. It runs in O(n) time and O(1) space. A DP or two-stack solution also works, but this greedy range-tracking is the elegant one.

Complexity

Time: O(n). Space: O(1).

Python solution
def checkValidString(s):
    lo = hi = 0
    for ch in s:
        if ch == '(':
            lo += 1; hi += 1
        elif ch == ')':
            lo -= 1; hi -= 1
        else:
            lo -= 1; hi += 1
        if hi < 0:
            return False
        lo = max(lo, 0)
    return lo == 0
JavaScript solution
function checkValidString(s) {
  let lo = 0, hi = 0;
  for (const ch of s) {
    if (ch === '(') { lo++; hi++; }
    else if (ch === ')') { lo--; hi--; }
    else { lo--; hi++; }
    if (hi < 0) return false;
    lo = Math.max(lo, 0);
  }
  return lo === 0;
}