SDE & MLE Prep

678. Valid Parenthesis String

Problem

s contains (, ) and *, where each * can act as (, as ) or as nothing. Decide whether s can be a valid parentheses string.

Example: "(*)" → true; "(*))" → true; ")(" → false

Constraints: length ≤ 100.

Track the range [lo, hi] of possible open counts. ( → both +1; ) → both −1; * → lo−1, hi+1. If hi < 0 fail; clamp lo ≥ 0. Valid iff lo == 0 at the end.

Complexity: O(n) time, O(1) space.

class Solution:
    def checkValidString(self, s: str) -> bool:
        lo = hi = 0
        for ch in s:
            if ch == "(":
                lo, hi = lo + 1, hi + 1
            elif ch == ")":
                lo, hi = lo - 1, hi - 1
            else:
                lo, hi = lo - 1, hi + 1
            if hi < 0:
                return False
            lo = max(lo, 0)
        return lo == 0