Valid Parenthesis String

MediumGreedy rangeLeetCode 678 ↗World 7-17
0:00 / 0:00

Check brackets where each star can be open, close or nothing. Track the lowest and highest possible open count instead of choosing.

▼

The problem

LeetCode 678 (Medium). Given a string of (, ) and *, where each * can be an open bracket, a close bracket or the empty string, return whether some choice of the stars makes the string a valid bracket sequence.

Examples (LeetCode's): "(*)" → true (the star is nothing), "(*))" → true (the star opens).

TRY IT ON LEETCODE ▶

The solution

def checkValidString(s):
    lo = hi = 0
    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
        if hi < 0:
            return False
        lo = max(lo, 0)
    return lo == 0

Transcript

Valid Parenthesis String. You get a string of open brackets, close brackets and stars. A star is a wild card: it can be an open bracket, a close bracket, or nothing. Can you pick the stars so the brackets balance?

Picture the string as a dive plan. An open bracket takes you one step deeper; a close brings you one step up. It balances if you never rise above the surface and you end right back at it. Open, star, close works: the star is nothing. Open, star, close, close works too: the star opens.

The easy way tries every choice. Each star has three, so two stars make nine plans, and k stars make three to the k. Twenty stars is over three billion plans.

The greedy trick: don't choose yet. Track every depth you could be at, from low to high. Send down two divers. An open bracket sinks both. A close lifts both. A star splits them: low rises, high sinks.

Two rules. If high breaks the surface, even the deepest plan has too many closes: fail. If low breaks the surface, that depth is impossible, so low bobs back to zero. At the end, it's valid if low is at the surface.

Let's dive open, star, close, close. Open: both at one. Star: low rises to zero, high sinks to two. Close: low would break the surface, so it stays at zero, and high comes up to one. Close: zero and zero. Low ends at the surface: valid. But open, open, star ends with low at one. One bracket never closes: false.

In code, low and high start at zero. Each character moves them both. If high is negative, return false. Clamp low at zero. At the end, return whether low is zero.

One pass, two numbers: order n time, order one space.

Don't choose, keep the range. That's Valid Parenthesis String.