Let's make this one less mysterious. For 678. Valid Parenthesis String, the solution in this repository is mainly a DFS + memoization solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: DFS + memoization, dynamic programming, prefix sums, bit manipulation.
The notes already sitting in the source point us in the right direction:
- Approach #1: Brute Force
- TLE
- 42 / 58 test cases passed.
- time: O(N*(3^N)), 3^N possible strings, check each string takes O(N)
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are valid, solve, checkValidString.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(N^3), space: O(N^2)
- Space: O(N)
Guide
C++ Solution
Your submission
The accepted solution
01//Approach #1: Brute Force
02//TLE
03//42 / 58 test cases passed.
04//time: O(N*(3^N)), 3^N possible strings, check each string takes O(N)
05//space: O(N)
06class Solution {
07public:
08 bool ans;
09
10 bool valid(string s){
11 int balance = 0;
12 for(char c : s){
13 switch(c){
14 case '(':
15 balance++;
16 break;
17 case ')':
18 balance--;
19 }
20 //in any prefix, we cannot have more ) than (
21 if(balance < 0) break;
22 }
23 return balance == 0;
24 };
25
26 void solve(string s, int i){
27 if(i == s.size()){
28 ans |= valid(s);
29 }else if(s[i] == '*'){
30 //interpret '*' as '(' or ')'
31 for(char c : "()"){
32 s[i] = c;
33 solve(s, i+1);
34 if(ans) return;
35 }
36 }else{
37 solve(s, i+1);
38 }
39 };
40
41 bool checkValidString(string s) {
42 ans = false;
43 solve(s, 0);
44 return ans;
45 }
46};
47
48//Approach #2: Dynamic Programming
49//Runtime: 44 ms, faster than 10.48% of C++ online submissions for Valid Parenthesis String.
50//Memory Usage: 6.7 MB, less than 100.00% of C++ online submissions for Valid Parenthesis String.
51//time: O(N^3), space: O(N^2)
52class Solution {
53public:
54 bool checkValidString(string s) {
55 int N = s.size();
56 if(N == 0) return true;
57 vector<vector<bool>> dp(N, vector<bool>(N, false));
58
59 //base case
60 for(int i = 0; i < N; i++){
61 if(s[i] == '*'){
62 dp[i][i] = true;
63 // cout << "[" << i << ", " << i << "]" << endl;
64 // cout << "true" << endl;
65 }
66 if(i < N-1 &&
67 (s[i] == '(' || s[i] == '*') &&
68 (s[i+1] == ')' || s[i+1] == '*')){
69 //i-1 and i can form a pair of ()
70 dp[i][i+1] = true;
71 // cout << "[" << i << ", " << i+1 << "]" << endl;
72 // cout << "true" << endl;
73 }
74 }
75
76 for(int width = 2; width < N; width++){
77 for(int start = 0; start + width < N; start++){
78 // cout << "[" << start << ", " << start+width << "]" << endl;
79 if(s[start] == '*' && dp[start+1][start+width]){
80 dp[start][start+width] = true;
81 // cout << "true" << endl;
82 }else if(s[start] == '(' || s[start] == '*'){
83 //find ')' or '*' in [start+1:start+width]
84 for(int k = start+1; k <= start+width; k++){
85 //s[start] and s[k] makes a pair
86 //dp[start+1][k-1] and dp[k+1][k+wdith] should be valid
87 if((s[k] == ')' || s[k] == '*') &&
88 (k == start+1 || dp[start+1][k-1]) &&
89 (k == start+width || dp[k+1][start+width])){
90 dp[start][start+width] = true;
91 // cout << "true" << endl;
92 }
93 }
94 }
95 }
96 }
97
98 return dp[0][N-1];
99 }
100};
101
102//Approach #3: Greedy
103//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parenthesis String.
104//Memory Usage: 6 MB, less than 100.00% of C++ online submissions for Valid Parenthesis String.
105//time: O(N), space: O(1)
106class Solution {
107public:
108 bool checkValidString(string s) {
109 int lo = 0, hi = 0;
110 for(char c : s){
111 lo += (c == '(') ? 1 : -1;
112 hi += c != ')' ? 1 : -1;
113 //if there are more ) than ( in a prefix, it cannot be fixed
114 if(hi < 0) break;
115 lo = max(lo, 0);
116 // cout << lo << ", " << hi << endl;
117 }
118 // cout << lo << ", " << hi << endl;
119 // cout << endl;
120 return lo == 0;
121 }
122};
Cost