Let's make this one less mysterious. For 1614. Maximum Nesting Depth of the Parentheses, the solution in this repository is mainly a stack 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: stack.
The notes already sitting in the source point us in the right direction:
- stack
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 maxDepth.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- 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:
- 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) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//stack
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Nesting Depth of the Parentheses.
03//Memory Usage: 6.4 MB, less than 50.00% of C++ online submissions for Maximum Nesting Depth of the Parentheses.
04class Solution {
05public:
06 int maxDepth(string s) {
07 stack<char> stk;
08 int ans = 0;
09
10 for(char c : s){
11 if(c == '('){
12 stk.push('(');
13 ans = max(ans, (int)stk.size());
14 }else if(c == ')'){
15 if(!stk.empty() && stk.top() == '('){
16 stk.pop();
17 }else{
18 return -1;
19 }
20 }
21 }
22
23 return ans;
24 }
25};
26
27//not using stack
28//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Nesting Depth of the Parentheses.
29//Memory Usage: 6.4 MB, less than 50.00% of C++ online submissions for Maximum Nesting Depth of the Parentheses.
30class Solution {
31public:
32 int maxDepth(string s) {
33 int unmatched = 0;
34 int ans = 0;
35
36 for(char c : s){
37 if(c == '('){
38 ++unmatched;
39 ans = max(ans, unmatched);
40 }else if(c == ')'){
41 if(unmatched > 0){
42 --unmatched;
43 }else{
44 return -1;
45 }
46 }
47 }
48
49 return ans;
50 }
51};
Cost