← Whiteboard questions

Valid Parenthesis String

Check brackets that include a wildcard

DSA, Medium, Greedy

Which structure or algorithm, and what does it cost.

A string s has only the characters (, ) and *. Read each * as (, as ) or as nothing. A reading is balanced when every ( is closed by a later ), every ) closes an earlier (, and the pairs nest properly. Return True if some reading of the stars makes s balanced. Otherwise return False.

Examples

Input s = "(*()*"
Output True
Why read the first star as ) and the last star as nothing. The string becomes ()().
Input s = "*(()"
Output False
Why the star comes before both (, so it cannot close either one, and at least one ( stays open at the end.
Input s = "*"
Output True
Why read the star as nothing, and the empty string is balanced.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Without stars you only need to count the open brackets. What does that count become when a star is in the string?

Hint 2 the approach

A star makes the count of open brackets uncertain. Think about which values that count could take.

Hint 3 the key step

Track the lowest and highest open count still possible. Ask what each character does to them, what a negative value would mean, and what must hold at the end.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every reading of the stars, with 3 choices each. Check each reading with a single open-bracket counter. With k stars that is 3^k readings, each checked in O(n) time, so it only works for a few stars. A string with 40 stars has more than 10^19 readings.

Better method

Keep two stacks of positions, one for each ( and one for each *. Match each ) with a waiting ( if there is one, else with a star, else fail. At the end, match each leftover ( with a later star, latest first, and fail if one has no later star. This is O(n) time and O(n) memory, but the order of the positions needs care.

Best method

Track low and high, the fewest and the most open brackets that could still be unclosed. A ( adds 1 to both. A ) takes 1 from both. A * takes 1 from low and adds 1 to high. If high falls below 0, even the most generous reading has an unmatched ), so return False. If low falls below 0, set it to 0, because a negative count means a ) with nothing to close, and that star can be read another way. At the end, return whether low is 0. This is safe because each star turns a count c into c - 1, c or c + 1, so an unbroken range of counts stays an unbroken range. Tracking only the two ends covers every reading at once.

Hand trace

Run on (*()*. Start with low 0 and high 0. Character (: low 1, high 1. Character *: low 0, high 2. Character (: low 1, high 3. Character ): low 0, high 2. Character *: low would be -1, so it becomes 0, and high is 3. At the end low is 0, so the answer is True.

Code

def can_balance(s):
    low = high = 0                  # fewest and most open brackets still unclosed
    for ch in s:
        if ch == '(':
            low += 1
            high += 1
        elif ch == ')':
            low -= 1
            high -= 1
        else:
            low -= 1
            high += 1
        if high < 0:
            return False            # too many ')' even if every star opens
        low = max(low, 0)
    return low == 0

Time and memory

O(n) time, one pass. O(1) memory, two counters.

Common mistakes

  • Letting low go below 0. That claims a state with a ) that has nothing to close, which no reading allows. Reset it to 0.
  • Testing only that high is 0 at the end. Some reading must close everything, so the test is that low is 0.
  • Treating a star as ( or ) only. It has a third reading, as nothing.
  • Not failing when high falls below 0. A later star cannot undo a ) that came before it.

Related problems

More Greedy problems
Valid Parenthesis String: walkthrough and Python solution