The trick here is to name the state correctly, then let the implementation follow. For 20. Valid Parentheses, the solution in this repository is mainly a two pointers 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: two pointers, stack.
The notes already sitting in the source point us in the right direction:
- time complexity: O(n), space complexity: O(n)
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isValid.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- A set is doing the membership or uniqueness work, which keeps the main loop readable.
- The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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), space complexity: O(n)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
02//Memory Usage: 8.5 MB, less than 99.87% of C++ online submissions for Valid Parentheses.
03//time complexity: O(n), space complexity: O(n)
04
05class Solution {
06public:
07 bool isValid(string s) {
08 map<char, char> paren;
09 paren['('] = ')';
10 paren['{'] = '}';
11 paren['['] = ']';
12
13 set<char> keys = {'(', '{', '['};
14
15 stack<char> stk;
16
17 for(char c : s){
18 if(keys.find(c) != keys.end()){//left
19 stk.push(c);
20 }else if(!stk.empty() && paren[stk.top()] == c){//right, match
21 stk.pop();
22 }else{//right, not match
23 return false;
24 }
25 }
26
27 return stk.empty();
28 }
29};
Cost