mediumStackGreedyGreedy

Valid Parenthesis String

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

Recognize the pattern

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

Brute force idea

The naive version of Valid Parenthesis String sounds like this: 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.

Better approach

The deeper shift in Valid Parenthesis String is this: 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.

Key invariant

At the center of Valid Parenthesis String is one steady idea: 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.

Watch out for

One easy way to drift off course in Valid Parenthesis String is this: 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