CodingNodes / Greedy / Valid Parenthesis String System design Space play · ←→ step · R restart

Problem

A string s contains only (, ) and *. Each * may be turned into (, into ), or deleted.

Return true if some way of choosing makes the parentheses balanced: every ( is closed by a later ), and no ) appears without an open one before it.

Constraints

  • 1 ≤ s.length ≤ 100
  • s contains only '(', ')' and '*'

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass, with constant work per character.

Space: Only two counters are stored.

Instead of guessing each star, track the range [lo, hi] of how many open parentheses are possible. A '(' raises both ends, a ')' lowers both, and a '*' lowers lo and raises hi. If hi ever drops below 0, too many ')' came too early and the answer is false. Keep lo at 0 or more, since a count cannot be negative. At the end the string is valid exactly when 0 is still in the range, meaning lo is 0.