Python coding

Balanced parentheses with wildcards

The string s holds only (, ) and *. Each * can stand for (, for ) or for nothing. Return True if some choice for the stars makes s balanced: every ( is closed by a later ), and no ) appears without an earlier unclosed (.

An empty string is balanced. Aim for one pass and O(1) extra space.

Besides the tests, one large input (a 4,000-character string) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • can_balance("((*)") → true
  • can_balance("(*)(*)(") → false
  • can_balance("*)(*)*)") → true
  • can_balance(")*(") → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Without stars you would count the open (. With stars that count is not one number but a range of possible values: keep its lowest and its highest value.

Hint 2

( raises both ends, ) lowers both, and * lowers the low end and raises the high one. If the high end drops below zero, fail; never let the low end go below zero.

Hint 3

At the end the string can be balanced exactly when the low end is 0. The trap is trying every replacement for the stars: that is 3^k strings.

Solution and why it works
pythonO(n) · O(1)
def can_balance(s: str) -> bool:
    low = high = 0                       # fewest and most '(' that could be open
    for ch in s:
        if ch == '(':
            low, high = low + 1, high + 1
        elif ch == ')':
            low, high = low - 1, high - 1
        else:                            # '*' closes one, adds nothing or opens one
            low, high = low - 1, high + 1
        if high < 0:                     # even with every star as '(' a ')' is unmatched
            return False
        low = max(low, 0)                # a star never has to close what isn't open
    return low == 0

Count open ( as you scan; with stars the count becomes a range. low turns stars into ) where it can, high turns every star into (, and every count in between is possible too, so two numbers summarize all 3^k choices. If high drops below zero, no choice saves that ). Clamp low at zero: a star that would close nothing becomes empty instead. Balanced iff low ends at 0. Skipping the clamp fails on "*(", and backtracking over the stars is exponential.