Valid Parenthesis String (LeetCode 678): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Start with
leftMin = 0andleftMax = 0. - For '(', add 1 to both. For ')', subtract 1 from both. For '*', subtract 1 from
leftMinand add 1 toleftMax. - If
leftMax < 0, there is no way to cover the closers seen so far, so return false. - If
leftMin < 0, reset it to 0, since negative open counts are not real states. - After the loop, return
leftMin == 0.
Step-by-step example
s = "(*))"
- '(':
leftMin = 1,leftMax = 1. - '*':
leftMin = 0,leftMax = 2. The star could close, vanish or open, so 0, 1 or 2 opens are possible. - ')':
leftMin = -1,leftMax = 1. ClampleftMinto 0, so the range is 0 to 1. - ')':
leftMin = -1,leftMax = 0.leftMaxis not negative, so continue, and clampleftMinto 0. - 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 == 01class Solution {
2 public boolean checkValidString(String s) {
3 int leftMin = 0, leftMax = 0;
4
5 for (int i = 0; i < s.length(); i++) {
6 char c = s.charAt(i);
7 if (c == '(') {
8 leftMin++;
9 leftMax++;
10 } else if (c == ')') {
11 leftMin--;
12 leftMax--;
13 } else {
14 leftMin--;
15 leftMax++;
16 }
17
18 if (leftMax < 0) return false;
19 if (leftMin < 0) leftMin = 0;
20 }
21 return leftMin == 0;
22 }
23}1class Solution {
2public:
3 bool checkValidString(string s) {
4 int leftMin = 0, leftMax = 0;
5
6 for (char c : s) {
7 if (c == '(') {
8 leftMin++;
9 leftMax++;
10 } else if (c == ')') {
11 leftMin--;
12 leftMax--;
13 } else {
14 leftMin--;
15 leftMax++;
16 }
17
18 if (leftMax < 0) return false;
19 if (leftMin < 0) leftMin = 0;
20 }
21 return leftMin == 0;
22 }
23};Time and space complexity
O(n)
The string is scanned once with constant work per character.
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
leftMaxinstead of failing when it goes negative. A negativeleftMaxmeans the string is already unrecoverable. - Forgetting to clamp
leftMinat zero, which lets impossible states with negative opens make a valid string look invalid at the end. - Returning
leftMax == 0or checking only thatleftMin <= 0at the end. The correct final test is whether zero lies in the range, which after clamping meansleftMin == 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.