Valid Parenthesis String
Valid Parenthesis String is a medium stack problem solved with the stack basics pattern.
The best approach, optimal (greedy range of open counts), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion with memo (position, open count) up.
Problem
You are given a string s made only of the characters '(', ')' and '*'. Each star is a wildcard: you may treat it as '(', as ')', or as if it were not there at all, and every star can be chosen independently.
Return true if some choice for the stars turns s into a balanced bracket string, and false otherwise. A string is balanced when every '(' is closed by a later ')', every ')' closes an earlier '(', and the pairs nest properly. The empty string counts as balanced.
Examples
Example 1
- Input
s = "((*)"- Output
true- Why
- Let the star act as a closing bracket: "(())" is balanced.
Example 2
- Input
s = "*)("- Output
false- Why
- The last character is an opening bracket with nothing after it to close it, whatever the star becomes.
Example 3
- Input
s = "(*)))"- Output
false- Why
- There are three closing brackets but at most two characters (the bracket and the star) can open, so some ')' is always unmatched.
Constraints
1 <= s.length <= 100- Every character of
sis'(',')'or'*'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 57 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursion with memo (position, open count) | O(n²) | O(n²) |
| Two stacks of indexes | O(n) | O(n) |
| Optimal (greedy range of open counts) | O(n) | O(1) |
1Recursion with memo (position, open count)
O(n²)There are at most (n + 1)² states (index, open), and each does constant work besides its three cached calls.O(n²)The memo table has (n + 1)² entries; the recursion is at most n deep.Walk the string while remembering how many brackets are open. A '(' adds one, a ')' removes one, and a star tries all three choices. The state is just (index, open), so caching it keeps the search polynomial.
- can(i, open) answers: can s[i..] be finished when
openbrackets are currently unclosed? - If open < 0, a ')' had nothing to match: false. At the end of the string, the answer is open == 0.
- If more brackets are open than characters remain, it cannot recover: false.
- '(' → can(i + 1, open + 1); ')' → can(i + 1, open - 1); '*' → any of the three.
- Store each answer in memo[i][open] before returning it.
class Solution {
private Boolean[][] memo;
private String s;
public boolean checkValidString(String s) {
this.s = s;
memo = new Boolean[s.length() + 1][s.length() + 2];
return can(0, 0);
}
private boolean can(int i, int open) {
if (open < 0) return false;
if (i == s.length()) return open == 0;
if (open > s.length() - i) return false;
if (memo[i][open] != null) return memo[i][open];
char c = s.charAt(i);
boolean ok;
if (c == '(') ok = can(i + 1, open + 1);
else if (c == ')') ok = can(i + 1, open - 1);
else ok = can(i + 1, open + 1) || can(i + 1, open - 1) || can(i + 1, open);
memo[i][open] = ok;
return ok;
}
}class Solution:
def checkValidString(self, s: str) -> bool:
n = len(s)
memo = {}
def can(i: int, open_: int) -> bool:
if open_ < 0:
return False
if i == n:
return open_ == 0
if open_ > n - i:
return False
if (i, open_) in memo:
return memo[(i, open_)]
c = s[i]
if c == '(':
ok = can(i + 1, open_ + 1)
elif c == ')':
ok = can(i + 1, open_ - 1)
else:
ok = can(i + 1, open_ + 1) or can(i + 1, open_ - 1) or can(i + 1, open_)
memo[(i, open_)] = ok
return ok
return can(0, 0)class Solution {
public:
bool checkValidString(string s) {
this->s = s;
int n = (int)s.size();
memo.assign(n + 1, vector<int>(n + 2, -1));
return can(0, 0);
}
private:
string s;
vector<vector<int>> memo;
bool can(int i, int open) {
if (open < 0) return false;
if (i == (int)s.size()) return open == 0;
if (open > (int)s.size() - i) return false;
if (memo[i][open] != -1) return memo[i][open];
char c = s[i];
bool ok;
if (c == '(') ok = can(i + 1, open + 1);
else if (c == ')') ok = can(i + 1, open - 1);
else ok = can(i + 1, open + 1) || can(i + 1, open - 1) || can(i + 1, open);
memo[i][open] = ok;
return ok;
}
};function checkValidString(s) {
const n = s.length;
const memo = Array.from({ length: n + 1 }, () => new Array(n + 2).fill(null));
function can(i, open) {
if (open < 0) return false;
if (i === n) return open === 0;
if (open > n - i) return false;
if (memo[i][open] !== null) return memo[i][open];
const c = s[i];
let ok;
if (c === '(') ok = can(i + 1, open + 1);
else if (c === ')') ok = can(i + 1, open - 1);
else ok = can(i + 1, open + 1) || can(i + 1, open - 1) || can(i + 1, open);
memo[i][open] = ok;
return ok;
}
return can(0, 0);
}2Two stacks of indexes
O(n)Every index is pushed once and popped at most once.O(n)The two stacks together hold at most n indexes.Keep the positions of unmatched '(' on one stack and of stars on another. A ')' prefers to close a real '(' and falls back to a star. At the end, every leftover '(' needs a star that comes after it.
- Push the index of every '(' onto
openand of every '*' ontostar. - On ')': pop
openif it is not empty, otherwise popstar; if both are empty, return false. - After the scan, while both stacks are non-empty: if the top '(' sits after the top star, that star cannot close it, so return false; otherwise pop both.
- Return true exactly when
openis empty (leftover stars just become empty).
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;
}
while (!open.isEmpty() && !star.isEmpty()) {
if (open.pop() > star.pop()) return false;
}
return open.isEmpty();
}
}class Solution:
def checkValidString(self, s: str) -> bool:
open_ = []
star = []
for i, c in enumerate(s):
if c == '(':
open_.append(i)
elif c == '*':
star.append(i)
elif open_:
open_.pop()
elif star:
star.pop()
else:
return False
while open_ and star:
if open_.pop() > star.pop():
return False
return not open_class Solution {
public:
bool checkValidString(string s) {
stack<int> open, star;
for (int i = 0; i < (int)s.size(); i++) {
char c = s[i];
if (c == '(') open.push(i);
else if (c == '*') star.push(i);
else if (!open.empty()) open.pop();
else if (!star.empty()) star.pop();
else return false;
}
while (!open.empty() && !star.empty()) {
int o = open.top(), t = star.top();
open.pop();
star.pop();
if (o > t) return false;
}
return open.empty();
}
};function checkValidString(s) {
const open = [], 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) open.pop();
else if (star.length) star.pop();
else return false;
}
while (open.length && star.length) {
if (open.pop() > star.pop()) return false;
}
return open.length === 0;
}3Optimal (greedy range of open counts)
O(n)One pass, constant work per character.O(1)Only the two counters lo and hi.After each prefix, the number of unclosed brackets could be any value in a range [lo, hi]: hi assumes every star opened, lo assumes every star closed. If even hi goes negative, too many ')' have appeared. A count below zero is never a real option, so lo is clamped at zero. At the end, zero must be reachable, which means lo == 0.
- Start with lo = hi = 0.
- '(' → lo++, hi++. ')' → lo--, hi--. '*' → lo-- (star closes), hi++ (star opens).
- If hi < 0, return false: no choice of stars can cover this many ')'.
- Set lo = max(lo, 0), dropping the impossible negative counts.
- After the scan, return lo == 0.
class Solution {
public boolean checkValidString(String s) {
int lo = 0, hi = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
lo++;
hi++;
} else if (c == ')') {
lo--;
hi--;
} else {
lo--;
hi++;
}
if (hi < 0) return false;
lo = Math.max(lo, 0);
}
return lo == 0;
}
}class Solution:
def checkValidString(self, s: str) -> bool:
lo = hi = 0
for c in s:
if c == '(':
lo += 1
hi += 1
elif c == ')':
lo -= 1
hi -= 1
else:
lo -= 1
hi += 1
if hi < 0:
return False
lo = max(lo, 0)
return lo == 0class Solution {
public:
bool checkValidString(string s) {
int lo = 0, hi = 0;
for (int i = 0; i < (int)s.size(); i++) {
char c = s[i];
if (c == '(') {
lo++;
hi++;
} else if (c == ')') {
lo--;
hi--;
} else {
lo--;
hi++;
}
if (hi < 0) return false;
lo = max(lo, 0);
}
return lo == 0;
}
};function checkValidString(s) {
let lo = 0, hi = 0;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === '(') {
lo++;
hi++;
} else if (c === ')') {
lo--;
hi--;
} else {
lo--;
hi++;
}
if (hi < 0) return false;
lo = Math.max(lo, 0);
}
return lo === 0;
}Edge cases to test
- A single star (valid: it becomes empty)
- A single bracket of either kind (invalid)
- Only stars (always valid)
- A star that appears after an unmatched '(' can close it, but one that appears before it cannot
- More ')' than '(' plus '*' (invalid at the first such point)
Hints
Hint 1
Without stars, a counter of open brackets is enough: it must never go below zero and must end at zero.
Hint 2
With stars the counter is no longer one number. Which values can it take after each character?
Hint 3
The possible open counts after each prefix form a whole range [lo, hi]. Track only its two ends, never let lo go below zero, and fail if hi drops below zero.
FAQ
What is the best time complexity for Valid Parenthesis String?
Optimal (greedy range of open counts) runs in O(n) time and O(1) extra space. One pass, constant work per character.
Which pattern does Valid Parenthesis String use?
It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.
Is there a brute force solution for Valid Parenthesis String?
Yes. Recursion with memo (position, open count) takes O(n²) time and O(n²) space. Walk the string while remembering how many brackets are open.
Which edge cases should I test for Valid Parenthesis String?
A single star (valid: it becomes empty); A single bracket of either kind (invalid); Only stars (always valid); A star that appears after an unmatched '(' can close it, but one that appears before it cannot; More ')' than '(' plus '' (invalid at the first such point).