Greedy Algorithms8 sections · 316 units
Open in Course

Valid Parenthesis - Greedy Range

Track min and max

Track lolo (min possible open count) and hihi (max possible open count). For '(': both increase by 11. For ')': both decrease by 11. For '*': lolo decreases (could be ')'), hihi increases (could be '('). Keep lo0lo \geq 0 (clamp it).

If hi<0hi < 0, there are too many ')' no matter what. At end, check lo=0lo = 0. The range [lo,hi][lo, hi] represents the minimum and maximum possible open parentheses count at each position.

If hi<0hi < 0, there are too many ')' no matter how you assign '*'.

If lo=0lo = 0 at the end, some assignment of '*' balances the string. Clamping lolo to 00 handles impossible negative counts.