Opening the reading…
Opening the reading…
STACK › PARENTHESES PROBLEM
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →At any position in a valid parentheses string, every opening parenthesis that has not yet been closed contributes one level of nesting. Count the opening parentheses seen so far, then subtract the closing parentheses seen so far. The result is the number of currently active layers around the position. Digits and operators do not change that count because they add no parentheses layer.
Whenever you read an opening parenthesis, the current depth increases by one, so that new depth may be the largest seen. Whenever you read a closing parenthesis, one layer ends and the depth decreases by one. The answer is therefore not the final depth, which is zero for a valid string, but the largest value reached during the scan.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Each of the n characters is examined once, with only constant work for each character, so no character is revisited or processed through a nested operation. |
| Space | O(1) extra | The algorithm stores only two integer counters, regardless of the input shape. The input string and returned integer are not working storage, and even a string with maximum possible nesting does not increase the extra space. |
#include <string>
using namespace std;
class Solution {
public:
int maxDepth(string s) {
int depth = 0;
int maxDepth = 0;
for (char c : s) {
if (c == '(') {
depth++;
if (depth > maxDepth) {
maxDepth = depth;
}
} else if (c == ')') {
depth--;
}
}
return maxDepth;
}
};The placement of the maximum update is the key detail. An opening parenthesis creates the depth that exists inside its pair, so you record the new value immediately. The later closing parenthesis only marks the end of that layer. Because the string is guaranteed valid, the counter returns to zero after the scan, but that final value is not the answer.