Skip to content
Problem 678 · LeetCode 678(opens in a new tab)

Valid Parenthesis String

MediumDynamic programming

You get a string s made of three characters: (, ) and *. Each * is a wildcard: you may read it as (, as ), or as nothing at all, and every star is chosen on its own.

Return true if some choice for the stars turns s into a balanced bracket string: every ( is closed by a later ), and no ) appears without an earlier ( to close.

Example 1

Input:  s = "(*)*)"
Output: true
Why:    read the first star as "(" and the second as nothing
2 more examples and the constraints

Example 2

Input:  s = "())*"
Output: false
Why:    the second ")" has no "(" before it to close

Example 3

Input:  s = "*"
Output: true
Why:    read the star as nothing: the empty string

Constraints

  • 1 ≤ length of s ≤ 100
  • Every character is (, ) or *

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every possible open countO(n²)
  2. Two stacks of indexesO(n)
  3. Low and high open countsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 charactersVerdict
Every possible open countO(n²)
Passes; easy to reason about
Two stacks of indexesO(n)
Passes; O(n) memory
Low and high open countsO(n)
Best; one pass, two numbers

n = length of s. Trying all 3^k star choices (k stars) is far worse than all three.

Edge cases to test

  • Only stars. A string of nothing but stars, even a single *, is always true: read every star as nothing.
  • A star before an open bracket. "*(" is false: the star cannot close a bracket to its right.
  • A close bracket first. ")" or ")*" fails at once: nothing before it can open.
  • Stars covering many opens. Three ( followed by three stars is true, with every star read as ).

Common mistakes

  • Comparing the number of stars with the number of open brackets without checking which comes first.
  • Forgetting to clamp lo at 0, so a star read as ")" seems to close a bracket that is not there.
  • Returning false when lo goes negative instead of when hi does.

How to talk through it

  1. 1Clarify. Is each star chosen on its own? Is the empty string balanced (so "*" alone is true)?
  2. 2Start from the brute force. Three meanings per star is 3^k strings; only the open count matters, so track the set of counts.
  3. 3Notice the range. The possible counts are always one unbroken range, so two numbers describe them.
  4. 4Code lo and hi. Explain the early false when hi < 0 and the clamp of lo at 0.
  5. 5Test out loud. Run "*(", "(*)*)" and a single star before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?