mediumStackGreedyGreedy

Valid Parenthesis String

mediumTime: O(n)Space: O(1)

Signals to notice

can string with * be valid parentheses* can be ( or ) or emptygreedy range tracking

Brute force first

Try all 3^k possibilities for each *. Exponential in the number of wildcards. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Track a range [minOpen, maxOpen] of possible open-paren counts. '(' increases both. ')' decreases both. '*' decreases min, increases max. Clamp min to 0. Valid if min can reach 0 at end. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

minOpen = minimum possible unmatched '(' (treat * as ')'). maxOpen = maximum possible unmatched '(' (treat * as '('). If maxOpen < 0, too many ')'. If minOpen == 0 at end, it's valid. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Only tracking one count — you need a range because '*' creates branching. The range collapses the exponential branches into two linear bounds. The fix is usually to return to the meaning of each move, not just the steps themselves.

Greedy Pattern