Valid Parenthesis String

Difficulty: Medium

You're given a string of '(', ')', and '*'. Each '*' is a wildcard: you choose whether it's '(', ')', or an empty string, separately for each one.

Return whether some choice of wildcards makes the string valid: every open paren has a matching close paren later, properly nested.

Examples

Input: s = "()"
Output: true

Already valid with no wildcards involved.

Input: s = "(*)"
Output: true

Treat the "*" as an empty string, leaving "()", which is valid.

Input: s = "(*))"
Output: true

Treat the "*" as "(", giving "(())", which is valid.

Constraints

  • 1 <= s.length <= 100

  • s[i] is '(', ')', or '*'

Approach

Trying every wildcard combination is exponential. Instead of one exact count of unmatched '(', track a range: the minimum and maximum unmatched count possible after each character.

Scan left to right:

  • '(' raises both bounds.
  • ')' lowers both.
  • '*' lowers the low bound (as ')') and raises the high bound (as '(').

If the high bound drops below 0, some ')' can't be matched whatever you choose, so fail. If the low bound drops below 0, clamp it to 0: that low path is dead, but higher ones may still work. At the end, the string is valid if the low bound is 0.

Solutions

Brute Force - Try Every Wildcard Resolution (Recursion)

At each '*', branch into all 3 choices and recursively check whether any leads to a valid string.

function checkValidString(s) {
  function isValid(i, openCount) {
    if (openCount < 0) return false;
    if (i === s.length) return openCount === 0;

    const c = s[i];
    if (c === "(") return isValid(i + 1, openCount + 1);
    if (c === ")") return isValid(i + 1, openCount - 1);
    // '*' — try treating it as '(', ')', or empty
    return (
      isValid(i + 1, openCount + 1) ||
      isValid(i + 1, openCount - 1) ||
      isValid(i + 1, openCount)
    );
  }
  return isValid(0, 0);
}

Time: O(3^n) in the worst case, one branch per wildcard interpretation · Space: O(n) recursion depth

Optimal - Track Range of Possible Open Counts

Track the minimum and maximum possible open count as you scan. '(' and ')' shift the range; '*' widens it.

function checkValidString(s) {
  let low = 0;
  let high = 0;

  for (const c of s) {
    if (c === "(") {
      low++;
      high++;
    } else if (c === ")") {
      low--;
      high--;
    } else {
      low--;
      high++;
    }

    if (high < 0) return false;
    if (low < 0) low = 0;
  }

  return low === 0;
}

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