Valid Parenthesis String

Pattern: Balanced brackets

medium

Track the range of possible open counts. ( raises both ends, ) lowers both, and * could be either or nothing, so it lowers the low end and raises the high end. Fail if the high end goes negative; clip the low end at 0. Valid if the low end finishes at 0.

The problem

Given a string of (, ) and *, where each * may be (, ) or nothing, return whether some choice makes the brackets balanced. "(*)" and "(*))" are true; ")*" is false.

Think first

  • With only ( and ), what number decides validity?
  • What values can that number take after a *?
  • When is it certainly invalid?

Hints

    Brute force, and why it fails

    Try all 3^stars choices: exponential. A DP over (index, open count) is O(n²).

    The key insight

    All reachable open counts form one unbroken range, so two numbers, lo and hi, describe every choice at once.

    Dry run

    lo1
    hi1

    s = "(*))". After (: lo = 1, hi = 1.

    Step 1 of 4

    The plan

    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
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with two counters.

    Edge cases

    • Empty string: true.
    • Only stars: true.
    • A star before the first ( cannot close it.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean checkValidString(String s) {
            int lo = 0, hi = 0;                     // the range of possible open-bracket counts
            for (char c : s.toCharArray()) {
                if (c == '(') { lo++; hi++; }
                else if (c == ')') { lo--; hi--; }
                else { lo--; hi++; }                // '*' can close, open, or be empty
                if (hi < 0) return false;           // even the most generous choice is too many ')'
                if (lo < 0) lo = 0;                 // counts below 0 are not allowed, so clip
            }
            return lo == 0;                         // some choice ends exactly balanced
        }
    }

    C++

    class Solution {
    public:
        bool checkValidString(string s) {
            int lo = 0, hi = 0;                     // the range of possible open-bracket counts
            for (char c : s) {
                if (c == '(') { lo++; hi++; }
                else if (c == ')') { lo--; hi--; }
                else { lo--; hi++; }                // '*' can close, open, or be empty
                if (hi < 0) return false;           // even the most generous choice is too many ')'
                if (lo < 0) lo = 0;                 // counts below 0 are not allowed, so clip
            }
            return lo == 0;                         // some choice ends exactly balanced
        }
    };

    Python

    class Solution:
        def checkValidString(self, s: str) -> bool:
            lo = hi = 0                             # the range of possible open-bracket counts
            for c in s:
                if c == "(":
                    lo, hi = lo + 1, hi + 1
                elif c == ")":
                    lo, hi = lo - 1, hi - 1
                else:
                    lo, hi = lo - 1, hi + 1         # '*' can close, open, or be empty
                if hi < 0:
                    return False                    # even the most generous choice is too many ')'
                lo = max(lo, 0)                     # counts below 0 are not allowed, so clip
            return lo == 0                          # some choice ends exactly balanced

    Common mistakes

    • Not clipping lo at 0, so a negative count is treated as reachable.
    • Returning hi == 0 instead of lo == 0.

    Similar problems