Algorithms · Visualized

Valid Parenthesis String

Greedy

Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.

Checks if a string containing '(', ')', and '*' (a wildcard that can act as '(', ')', or empty) can be interpreted as a valid balanced parenthesis sequence. Time: O(n) average, O(n) worst; space: O(1).

Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.

Valid Parenthesis String

Greedy

Checks if a string containing '(', ')', and '*' (a wildcard that can act as '(', ')', or empty) can be interpreted as a valid balanced parenthesis sequence. The greedy trick: track a range [low, high] of the possible number of 'open' parentheses at each point, since '*' creates ambiguity — low assumes '*' closes/empties, high assumes '*' opens.

How Valid Parenthesis String Works

  1. Track two counters: 'low' (minimum possible open-parenthesis count) and 'high' (maximum possible open-parenthesis count), both starting at 0.
  2. For each character: if it's '(', increment both low and high. If it's ')', decrement both low and high. If it's '*', decrement low (treating it as a potential close) and increment high (treating it as a potential open).
  3. If 'high' ever drops below 0, there's no way to balance the string from here — return false immediately.
  4. Clamp 'low' at 0 whenever it would go negative (since low can't represent an invalid state — it just means that interpretation isn't the binding constraint).
  5. After processing the whole string, it's valid if 'low' has reached exactly 0 (there's an interpretation where everything balances).

Valid Parenthesis String Worked Example

Input: (*))

'(' → low=1,high=1. '*' → low=0(clamped),high=2. ')' → low=-1→clamp to0, high=1. ')' → low would be -1→clamp to0, high=0. End: high never went negative, and low=0 at the end → valid, return true.

Valid Parenthesis StringO(n)
With `*` as wildcard, track the range of possible open counts.
(
0
*
1
)
2
)
3
Step 1 / 6
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Valid Parenthesis String: `*` acts as `(`, `)`, or empty. Track the range of possible open brackets.
Python · Greedy Algorithms in Code
def valid_parenthesis_string(s):
    lo = hi = 0
    for c in s:
        if c == '(':
            lo += 1
        else:
            lo = max(lo - 1, 0)
        if c == ')':
            hi -= 1
        else:
            hi += 1
        if hi < 0:
            return False
    return lo == 0

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Valid Parenthesis String Time & Space Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

When to Use Valid Parenthesis String

  • Validating expressions or code with wildcard/optional tokens, such as flexible syntax checkers or template validators.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.