678. Valid Parenthesis String
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Greedy
- Time
- O(n)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a string containing '(', ')', and '*' (which can act as '(', ')', or empty string), determine whether the string can represent a valid parenthesis sequence.
Approach
- Track a range
[lo, hi]representing the minimum and maximum possible number of unmatched open parentheses at each step. - '(' increments both bounds; ')' decrements both; '*' widens the range by decrementing
loand incrementinghi. - If
hiever drops below zero, more ')' have appeared than any assignment of '*' can compensate — return false immediately. - Clamp
loto zero (we can never have a negative open count) and, after processing all characters, the string is valid ifflo == 0.
#include <string>
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
// lo = minimum possible open-paren count
// hi = maximum possible open-paren count
int lo = 0, hi = 0;
for (char c : s) {
if (c == '(') {
++lo; ++hi;
} else if (c == ')') {
--lo; --hi;
} else { // '*' can be '(', ')', or ""
--lo; ++hi;
}
// More ')' than any '*' assignment can fix
if (hi < 0) return false;
// Open count cannot go negative; clamp lo
if (lo < 0) lo = 0;
}
// Valid iff it is possible to have zero unmatched opens
return lo == 0;
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <string>
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
int lmin=0;
int lmax=0;
for(const char c: s){
if(c=='('){
++lmin;
++lmax;
}
else if(c==')'){
--lmin;
--lmax;
}
else{ // c=='*'
--lmin;
++lmax;
}
if(lmax<0){
return false;
}
if(lmin<0){
lmin=0;
}
}
return lmin==0;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) Time O(n) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.