Valid Parenthesis String (LeetCode 678): Solution and Explanation

Medium
String
Dynamic Programming
Stack
Greedy

A string contains '(', ')' and '*', where each '*' can act as an opening parenthesis, a closing parenthesis or nothing. Decide whether some choice for the stars makes the whole string a balanced set of parentheses.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without stars, the classic check keeps a counter of unmatched open parentheses: add one for '(', subtract one for ')', fail if it ever goes negative, and succeed if it ends at zero. Stars break this because each one has three possible meanings. Trying every combination is 3^s for s stars, which is far too many, and even a memoized search over (index, open count) is O(n²).

The trick is to stop tracking a single open count and instead track the range of counts that are possible after each character. Let leftMin be the smallest number of unmatched opens you could have and leftMax the largest. An opening parenthesis raises both by one. A closing parenthesis lowers both by one. A star could be any of the three, so it lowers leftMin (treat it as ')') and raises leftMax (treat it as '(').

Two rules keep the range honest. If leftMax drops below zero, then even treating every star as '(' leaves too many closers, so the string is invalid right away. If leftMin drops below zero, that particular choice would mean more closers than openers, which is never allowed, so clamp it back to zero; the corresponding star should have been an empty string instead. At the end, the string is valid exactly when zero is in the range, which means leftMin == 0.

Approach: Greedy range of open counts

  1. Start with leftMin = 0 and leftMax = 0.
  2. For '(', add 1 to both. For ')', subtract 1 from both. For '*', subtract 1 from leftMin and add 1 to leftMax.
  3. If leftMax < 0, there is no way to cover the closers seen so far, so return false.
  4. If leftMin < 0, reset it to 0, since negative open counts are not real states.
  5. After the loop, return leftMin == 0.

Step-by-step example

s = "(*))"
  1. '(': leftMin = 1, leftMax = 1.
  2. '*': leftMin = 0, leftMax = 2. The star could close, vanish or open, so 0, 1 or 2 opens are possible.
  3. ')': leftMin = -1, leftMax = 1. Clamp leftMin to 0, so the range is 0 to 1.
  4. ')': leftMin = -1, leftMax = 0. leftMax is not negative, so continue, and clamp leftMin to 0.
  5. The loop ends with leftMin = 0, so return true. Treating the star as '(' gives "(())".

Code: Python, Java, C++

1class Solution:
2    def checkValidString(self, s: str) -> bool:
3        leftMin, leftMax = 0, 0
4        
5        for c in s:
6            if c == "(":
7                leftMin, leftMax = leftMin + 1, leftMax + 1
8            elif c == ")":
9                leftMin, leftMax = leftMin - 1, leftMax - 1
10            else:
11                leftMin, leftMax = leftMin - 1, leftMax + 1
12                
13            if leftMax < 0:
14                return False
15            if leftMin < 0:
16                leftMin = 0
17                
18        return leftMin == 0

Time and space complexity

Time

O(n)

The string is scanned once with constant work per character.

Space

O(1)

Only the two integers leftMin and leftMax are stored.

Other approaches

Two stacks of indices (time O(n), space O(n))

Push indices of '(' onto one stack and '*' onto another. Match each ')' with an open paren if possible, otherwise with a star. At the end, pair leftover open parens with stars that appear after them. It is intuitive and linear but uses extra memory.

Dynamic programming on index and open count (time O(n²), space O(n²))

Let dp[i][j] say whether the suffix from i can be balanced given j unmatched opens. Stars branch three ways. It is the most straightforward correct method to derive but is quadratic.

Common mistakes

  • Clamping leftMax instead of failing when it goes negative. A negative leftMax means the string is already unrecoverable.
  • Forgetting to clamp leftMin at zero, which lets impossible states with negative opens make a valid string look invalid at the end.
  • Returning leftMax == 0 or checking only that leftMin <= 0 at the end. The correct final test is whether zero lies in the range, which after clamping means leftMin == 0.
  • Counting stars separately and comparing totals, which ignores order. In "*(" the star comes before the open paren and cannot close it.

Frequently asked questions

Why do we track a minimum and maximum number of open parentheses?

Each star can be '(', ')' or empty, so after each character there is a range of possible open counts rather than one value. Tracking only the endpoints captures every possibility in constant space, since every count in between is also reachable.

Why reset leftMin to zero when it goes negative?

A negative open count would mean a closer with nothing to match, which is invalid. Choosing that star as empty instead of ')' keeps the count at zero, so zero is the true minimum.

Is there a stack solution for valid parenthesis string?

Yes. Keep separate stacks of indices for '(' and '*', match closers greedily, and at the end match remaining opens with later stars. It is also O(n) but uses O(n) space.