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
GreedyChecks 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
- Track two counters: 'low' (minimum possible open-parenthesis count) and 'high' (maximum possible open-parenthesis count), both starting at 0.
- 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).
- If 'high' ever drops below 0, there's no way to balance the string from here — return false immediately.
- 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).
- 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.
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 == 0Behind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.