15% off all plans & roadmaps Use code
See plansValid Parenthesis String
- LeetCode 678
- Medium
- Stack Patterns
- Valid Parentheses Matching
Updated
TL;DR: Decide whether the wildcards in a string of `(`, `)` and `*` can be set so the parentheses balance. Track the lowest and highest possible count of open parentheses in one pass.
Problem
You are given a string s made of three kinds of characters: (, ) and *. Decide whether it can be read as a correctly balanced parenthesis sequence.
Each * can be treated as a single (, a single ), or an empty string. Every other character keeps its normal meaning. Return true if some choice for every * gives a valid sequence, and false otherwise.
A valid sequence has every ( matched by a later ), and no ) appears before the ( it closes.
Example 1
Input: s = "(*()" Output: true Explanation: Treat the * as ) to get (()), which is balanced.
Example 2
Input: s = "())*" Output: false Explanation: The first three characters already contain one unmatched ), and the final * comes too late to fix that.
Example 3
Input: s = "***" Output: true Explanation: Treat the wildcards as (, ) and empty to get ().
Constraints
1 <= s.length <= 10^5- Each character of
sis(,)or*.
Constraints that matter
- n up to 10^5 rules out trying every interpretation. With k wildcards there are 3^k of them, so the search must be summarised, not enumerated.
- n up to 10^5 also rules out an O(n^2) table of (index, balance) states if you want a safe margin. A linear scan is the target.
- The alphabet has only three characters, so the whole state of a prefix is one number: how many
(are still open. Wildcards make that number uncertain, not complicated. - Only the count of open parentheses matters, not which ones. That is why two integers or two stacks of indices are enough.
Hints
Hint 1
This is a valid parentheses matching problem.
Hint 2
Try every reading of every star.
Solution
Intuition
This is a valid parentheses matching problem. In a plain string you scan left to right and keep one number: the count of unmatched (. It must never drop below zero, and it must be zero at the end.
Picture a needle that can rest anywhere between two stops on a dial. The low stop is every star acting as a closing bracket, and the high stop is every star acting as an opening bracket.
A * breaks the single number, because it can add one, subtract one, or change nothing. After a few stars you hold many possible counts at once. The reachable counts form a contiguous range. If a count of 3 and a count of 1 are both reachable, then 2 is reachable too, since you can turn one more star into an empty character.
A contiguous range needs only two numbers: the lowest reachable count and the highest. The highest count assumes every star is (. The lowest assumes every star is ), but never goes below zero, because a count below zero means a ) had nothing to close and that branch is dead.
Two checks finish the job. If the highest count goes below zero, even the best reading has too many ), so you stop with false. At the end, the string works if zero is in the range, and since the lowest count is clamped at zero, that means the lowest count equals zero.
The same idea has a stack version. Keep the indices of unmatched ( in one stack and the indices of stars in another. A ) consumes a ( if one exists, otherwise a star. Leftover ( need a star that appears after them.
Worked example
Input: s = "(*()" Output: true Explanation: The * at index 1 can act as ). The string then reads (()), where the first ( closes with the ) from the star and the second ( closes with the final ).
Approach 1: Brute force recursion
Try every reading of every star. Walk the string with a running balance of open parentheses. For ( add one, for ) subtract one, and for * branch into three calls: empty, ) and (.
A branch dies as soon as the balance goes below zero. A branch succeeds if it reaches the end with balance zero. With k stars there can be 3^k branches, so this is correct but exponential.
Memoising on the pair (index, balance) cuts the work to O(n^2) states, since the balance never exceeds n. That is still too much for n = 10^5, and it hides a simpler fact: the reachable balances form a range.
Steps
- Define
dfs(i, bal)as: can the suffix starting atifinish with balance zero, given the current balancebal. - If
bal < 0, return false, because a)has no partner. - If
iis the string length, return whetherbal == 0. - For
(, recurse withbal + 1. For), recurse withbal - 1. - For
*, return true if any of the three calls succeeds:bal,bal - 1,bal + 1. - Start with
dfs(0, 0).
Dry run
On (*() the call tree is small.
dfs(0,0):(leads todfs(1,1).dfs(1,1)is the star. Try empty first:dfs(2,1). The(givesdfs(3,2), the)givesdfs(4,1). The end is reached with balance 1, so false.- Back at the star, try
):dfs(2,0). The(givesdfs(3,1), the)givesdfs(4,0). The end is reached with balance 0, so true.
The star branch returns true, so the answer is true. Two of the three star choices were explored before success.
Complexity
| Time | O(3^k) where k is the number of stars |
|---|---|
| Space | O(n) recursion depth |
Let n be the string length and k the number of stars. Each star starts up to three calls, and every other character starts one, so the call tree has at most 3^k leaves. Each call does O(1) work, giving O(3^k) time up to a factor of n for the path length. The recursion goes one level per character, so the stack depth is n, which is O(n) space.
PythonTested in our runner
from typing import List, Optional
from functools import lru_cache
import sys
class Solution:
def checkValidString(self, s: str) -> bool:
n = len(s)
# suffix count of parens left to bound the balance
sys.setrecursionlimit(max(10000, 4 * n + 100))
# remaining[i] = number of chars from i to end; balance above that can never close
memo = set()
def dfs(i: int, bal: int) -> bool:
if bal < 0 or bal > n - i:
return False
if i == n:
return bal == 0
if (i, bal) in memo:
return False # already explored and failed
c = s[i]
if c == '(':
res = dfs(i + 1, bal + 1)
elif c == ')':
res = dfs(i + 1, bal - 1)
else:
# star: empty, close, or open
res = dfs(i + 1, bal) or dfs(i + 1, bal - 1) or dfs(i + 1, bal + 1)
if not res:
memo.add((i, bal))
return res
return dfs(0, 0)C++Tested in our runner
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
return dfs(s, 0, 0);
}
private:
bool dfs(const string& s, int i, int bal) {
if (bal < 0) return false;
if (i == (int)s.size()) return bal == 0;
char c = s[i];
if (c == '(') return dfs(s, i + 1, bal + 1);
if (c == ')') return dfs(s, i + 1, bal - 1);
// star: empty, close, or open
return dfs(s, i + 1, bal) || dfs(s, i + 1, bal - 1) || dfs(s, i + 1, bal + 1);
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
const n = s.length;
// cur[b] = 1 if balance b is reachable after the processed prefix (memoised on (index, balance), iterative)
let cur = new Uint8Array(n + 2);
cur[0] = 1;
for (let i = 0; i < n; i++) {
const c = s[i];
const next = new Uint8Array(n + 2);
for (let b = 0; b <= i; b++) {
if (!cur[b]) continue;
if (c === '(') {
next[b + 1] = 1;
} else if (c === ')') {
if (b > 0) next[b - 1] = 1;
} else {
// star: empty, open or close
next[b] = 1;
next[b + 1] = 1;
if (b > 0) next[b - 1] = 1;
}
}
cur = next;
}
return cur[0] === 1;
};GoTested in our runner
func checkValidString(s string) bool {
var dfs func(i, bal int) bool
dfs = func(i, bal int) bool {
if bal < 0 {
return false
}
if i == len(s) {
return bal == 0
}
switch s[i] {
case '(':
return dfs(i+1, bal+1)
case ')':
return dfs(i+1, bal-1)
}
// star: empty, close, or open
return dfs(i+1, bal) || dfs(i+1, bal-1) || dfs(i+1, bal+1)
}
return dfs(0, 0)
}C#Tested in our runner
public class Solution {
public bool checkValidString(string s) {
return Dfs(s, 0, 0);
}
private bool Dfs(string s, int i, int bal) {
if (bal < 0) return false;
if (i == s.Length) return bal == 0;
char c = s[i];
if (c == '(') return Dfs(s, i + 1, bal + 1);
if (c == ')') return Dfs(s, i + 1, bal - 1);
// star: empty, close, or open
return Dfs(s, i + 1, bal) || Dfs(s, i + 1, bal - 1) || Dfs(s, i + 1, bal + 1);
}
}
Solution pattern
Valid Parentheses Matching
Part of Stack Patterns
Approach 2: Two stacks of indicesValid Parentheses Matching
What's slow: the recursion explores each star three ways and revisits the same balances again and again. The balance is only a count, so the exact choice for each star is rarely needed.
The insight that fixes it: decide star roles lazily, using positions. Keep one stack of indices of unmatched ( and one of indices of stars. A ) should close a real ( first, because stars are flexible and worth saving. If no ( is open, the ) borrows a star. If neither exists, the string is dead.
After the scan, some ( may be left over. Each needs a star to its right, because that star must act as ) and a ) must come after its (. Match the leftover ( and stars from the top of the stacks, and check the order.
Steps
- Create two empty stacks,
openandstar, holding indices. - Scan left to right. Push
iontoopenfor(and ontostarfor*. - On
), pop fromopenif it is not empty. - Otherwise pop from
starif it is not empty. - Otherwise return false, because nothing can close this
). - After the scan, while both stacks are non-empty, pop one index from each. If the
(index is greater than the star index, return false. - Return true only if
openis empty.
Dry run
Trace (*().
- i=0
(:open = [0]. - i=1
*:star = [1]. - i=2
(:open = [0, 2]. - i=3
):openis not empty, so pop 2. Nowopen = [0]. - Scan ends with
open = [0]andstar = [1]. Pop both: the(at 0 is before the star at 1, so the star can close it. openis empty, so the answer istrue.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of s. Each index is pushed at most once and popped at most once, and the final matching loop pops each stack entry at most once. That is O(n) total work. In the worst case, such as (((( or ****, one stack holds about n indices, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def checkValidString(self, s: str) -> bool:
open_stack = []
star_stack = []
for i, c in enumerate(s):
if c == '(':
open_stack.append(i)
elif c == '*':
star_stack.append(i)
else:
if open_stack:
open_stack.pop()
elif star_stack:
star_stack.pop()
else:
return False
# each leftover '(' needs a star to its right
while open_stack and star_stack:
if open_stack.pop() > star_stack.pop():
return False
return not open_stackJavaTested in our runner
import java.util.*;
class Solution {
public boolean checkValidString(String s) {
Deque<Integer> open = new ArrayDeque<>();
Deque<Integer> star = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
open.push(i);
} else if (c == '*') {
star.push(i);
} else {
if (!open.isEmpty()) {
open.pop();
} else if (!star.isEmpty()) {
star.pop();
} else {
return false;
}
}
}
// each leftover '(' needs a star to its right
while (!open.isEmpty() && !star.isEmpty()) {
if (open.pop() > star.pop()) return false;
}
return open.isEmpty();
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
vector<int> open, star;
for (int i = 0; i < (int)s.size(); i++) {
char c = s[i];
if (c == '(') {
open.push_back(i);
} else if (c == '*') {
star.push_back(i);
} else {
if (!open.empty()) {
open.pop_back();
} else if (!star.empty()) {
star.pop_back();
} else {
return false;
}
}
}
// each leftover '(' needs a star to its right
while (!open.empty() && !star.empty()) {
if (open.back() > star.back()) return false;
open.pop_back();
star.pop_back();
}
return open.empty();
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
const open = [];
const star = [];
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === '(') {
open.push(i);
} else if (c === '*') {
star.push(i);
} else {
if (open.length > 0) {
open.pop();
} else if (star.length > 0) {
star.pop();
} else {
return false;
}
}
}
// each leftover '(' needs a star to its right
while (open.length > 0 && star.length > 0) {
if (open.pop() > star.pop()) return false;
}
return open.length === 0;
};GoTested in our runner
func checkValidString(s string) bool {
open := []int{}
star := []int{}
for i := 0; i < len(s); i++ {
switch s[i] {
case '(':
open = append(open, i)
case '*':
star = append(star, i)
default:
if len(open) > 0 {
open = open[:len(open)-1]
} else if len(star) > 0 {
star = star[:len(star)-1]
} else {
return false
}
}
}
// each leftover '(' needs a star to its right
for len(open) > 0 && len(star) > 0 {
o := open[len(open)-1]
t := star[len(star)-1]
open = open[:len(open)-1]
star = star[:len(star)-1]
if o > t {
return false
}
}
return len(open) == 0
}C#Tested in our runner
public class Solution {
public bool checkValidString(string s) {
var open = new Stack<int>();
var star = new Stack<int>();
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == '(') {
open.Push(i);
} else if (c == '*') {
star.Push(i);
} else {
if (open.Count > 0) {
open.Pop();
} else if (star.Count > 0) {
star.Pop();
} else {
return false;
}
}
}
// each leftover '(' needs a star to its right
while (open.Count > 0 && star.Count > 0) {
if (open.Pop() > star.Pop()) return false;
}
return open.Count == 0;
}
}Approach 3: Greedy range of open countsOptimal
What's slow: the two-stack version stores indices, but the answer depends only on how many ( can be open, not where they are. That costs O(n) space and a second pass for no gain.
The insight that fixes it: keep the lowest and highest possible open counts, low and high. A ( raises both. A ) lowers both.
A * lowers low (star as )) and raises high (star as (), and the unchanged choice sits between them. Clamp low at zero, because a negative count is not a real state. If high drops below zero, return false. At the end, accept when low == 0.
Steps
- Set
low = 0andhigh = 0. - For
(: incrementlowandhigh. - For
): decrementhigh, and setlow = max(0, low - 1). - For
*: incrementhigh, and setlow = max(0, low - 1). - After each character, if
high < 0, return false. - After the loop, return
low == 0.
Dry run
Trace (*() and watch the range [low, high].
| Step | Char | low | high | Note |
|---|---|---|---|---|
| start | 0 | 0 | only count 0 is possible | |
| 1 | ( | 1 | 1 | both bounds rise |
| 2 | * | 0 | 2 | low falls to 0 (star as )), high rises to 2 (star as () |
| 3 | ( | 1 | 3 | both bounds rise |
| 4 | ) | 0 | 2 | both fall, low stays at or above 0 |
| end | 0 | 2 | low == 0, so return true |
Zero is inside the final range, so some reading of the star balances the string. High never went negative.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of s. The loop visits each character once and does a constant number of comparisons and additions, so time is O(n). The only state is the two integers low and high, so space is O(1). Both values stay between 0 and n in magnitude, so they fit in a 32-bit int.
PythonTested in our runner
from typing import List, Optional
class Solution:
def checkValidString(self, s: str) -> bool:
low = 0 # fewest open '(' possible
high = 0 # most open '(' possible
for c in s:
if c == '(':
low += 1
high += 1
elif c == ')':
low = max(0, low - 1)
high -= 1
else:
low = max(0, low - 1)
high += 1
if high < 0: # too many ')' even in the best reading
return False
return low == 0JavaTested in our runner
import java.util.*;
class Solution {
public boolean checkValidString(String s) {
int low = 0; // fewest open '(' possible
int high = 0; // most open '(' possible
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
low++;
high++;
} else if (c == ')') {
low = Math.max(0, low - 1);
high--;
} else {
low = Math.max(0, low - 1);
high++;
}
if (high < 0) return false; // too many ')' even in the best reading
}
return low == 0;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
int low = 0; // fewest open '(' possible
int high = 0; // most open '(' possible
for (char c : s) {
if (c == '(') {
low++;
high++;
} else if (c == ')') {
low = max(0, low - 1);
high--;
} else {
low = max(0, low - 1);
high++;
}
if (high < 0) return false; // too many ')' even in the best reading
}
return low == 0;
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {boolean}
*/
var checkValidString = function(s) {
let low = 0; // fewest open '(' possible
let high = 0; // most open '(' possible
for (const c of s) {
if (c === '(') {
low++;
high++;
} else if (c === ')') {
low = Math.max(0, low - 1);
high--;
} else {
low = Math.max(0, low - 1);
high++;
}
if (high < 0) return false; // too many ')' even in the best reading
}
return low === 0;
};GoTested in our runner
func checkValidString(s string) bool {
low := 0 // fewest open '(' possible
high := 0 // most open '(' possible
for i := 0; i < len(s); i++ {
switch s[i] {
case '(':
low++
high++
case ')':
if low > 0 {
low--
}
high--
default:
if low > 0 {
low--
}
high++
}
if high < 0 { // too many ')' even in the best reading
return false
}
}
return low == 0
}C#Tested in our runner
public class Solution {
public bool checkValidString(string s) {
int low = 0; // fewest open '(' possible
int high = 0; // most open '(' possible
foreach (char c in s) {
if (c == '(') {
low++;
high++;
} else if (c == ')') {
low = Math.Max(0, low - 1);
high--;
} else {
low = Math.Max(0, low - 1);
high++;
}
if (high < 0) return false; // too many ')' even in the best reading
}
return low == 0;
}
}Common mistakes
- Forgetting the clamp, writing
low -= 1on)and*. Thenlowcan go negative, and inputs like)*can end with a false reading. Uselow = max(0, low - 1). - Checking
low < 0instead ofhigh < 0for the early exit.lowis clamped and never negative. The dead-prefix signal ishigh < 0, so test that after every character. - Returning
high == 0orlow == highat the end. The string is valid if zero is anywhere in the range, and sincelowis clamped, that meanslow == 0. Returnlow == 0. - Treating
*as only one fixed choice, for example always)when the balance is positive. That greedy rule fails on(*)(-style cases where a later(needs the star. Track the full range, or use the two-stack check with index order. - In the two-stack version, popping a star before a
(on). Stars are flexible and should be saved. Popopenfirst, then fall back tostar. - In the two-stack version, matching leftover
(and stars without comparing indices, as in*(. The star comes before the(, so it cannot close it. Compareopen.pop() > star.pop()and return false when the(is later.
Edge cases
*alone: the star can be empty, so the answer istrue. Herelowends at 0.(: one open parenthesis and no star, solowandhighboth end at 1 and the answer isfalse.):highbecomes -1 right away, so the answer isfalse.*(: the star comes before the(and cannot close it, so the answer isfalse. The range ends at[1, 2].(*)and(*)): the first istruewith the star empty. The second istruewith the star as(, giving(()).)(followed by stars, such as)(**:highgoes negative on the first character, so the answer isfalseno matter how many stars follow.- A string of 10^5 stars: the answer is
true. The greedy and stack solutions finish instantly, while the 3^k brute force never would.
Follow-ups interviewers ask
- Can you solve it with dynamic programming, and what does it cost?
- Yes. Let
dp[i][b]say whether the suffix fromican finish whenbparentheses are open. Each state has at most three transitions, andbis at most n, so time is O(n^2) and space O(n^2), or O(n) with a rolling row. It is correct but too slow for n = 10^5, and the greedy range replaces the whole table with two numbers. - Why is it safe to say every count between
lowandhighis reachable? - Each character changes the set of reachable counts by shifting it or by widening it with a star. Starting from {0}, a star turns a set {a..b} into {a-1..b+1}, which stays contiguous. A
(or)shifts the whole set, and clamping at zero removes only the negative end. Contiguous sets are fully described by their endpoints. - How would you also return one valid interpretation?
- Use the two-stack method. Record which star each
)borrowed and which star each leftover(pairs with. Turn those stars into)or(and every other star into empty. This takes O(n) time and space, since you must store the choices, which the O(1) space range cannot do.
Valid Parenthesis String FAQ
What is the time complexity of Valid Parenthesis String?
The optimal solution runs in O(n) time with O(1) extra space, where n is the length of the string. It reads each character once and updates two integers. The brute force recursion is O(3^k) for k stars, and a memoised DP is O(n^2).
Why use a greedy range for Valid Parenthesis String?
Only the number of open parentheses matters, and the reachable counts always form a contiguous range. Two integers, the lowest and highest count, describe that range exactly. You reject when the highest count goes below zero and accept when the lowest count is zero at the end.
Can Valid Parenthesis String be solved in O(1) extra space?
Yes. The low and high counters use constant space. A stack or DP table needs O(n), so the greedy range is the only one of these approaches that reaches O(1).
Why does `low` need to be clamped at zero?
A negative open count means a ) had no ( to close, and that reading is invalid, not a state to continue from. Clamping drops those dead readings and keeps the best live ones. Without it, low could be reported as zero or below by a reading that was already broken.
How do I check if a string of parentheses is valid without wildcards?
Scan left to right with one counter. Add one for (, subtract one for ), return false if the counter goes below zero, and return whether it is zero at the end. The wildcard version is the same idea with a range instead of one counter.
Why does the stack solution compare indices at the end?
A star used as ) must come after the ( it closes. If a leftover ( sits at index 5 and the matching star at index 3, that star cannot close it. The comparison open_index > star_index catches that case.
Asked at
See which companies ask this — Pro
Related problems
- Minimum Remove to Make Valid Parentheses · same technique: Valid Parentheses Matching
- Minimum Add to Make Parentheses Valid · same technique: Valid Parentheses Matching
- Minimum Number of Swaps to Make the String Balanced · same technique: Valid Parentheses Matching
- Longest Valid Parentheses · same technique: Valid Parentheses Matching
- Valid Parentheses · same technique: Valid Parentheses Matching
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns
- Car Fleet · same pattern: Stack Patterns
- Simplify Path · same pattern: Stack Patterns