Maximum Nesting Depth of the Parentheses
Easy · Stack · Explanation and code example
Iteration
How it works
We don't actually need to store the parentheses in a stack. Since we only care about the depth (stack size), we can replace the stack with a simple counter. This reduces space complexity to O(1) while maintaining the same logic.
Steps
- Initialize
res = 0to track the maximum depth andcur = 0to track the current depth. - Iterate through each character in the string.
- If the character is
(, incrementcur. If it's), decrementcur. - After each character, update
reswith the maximum ofresandcur. - Return
res.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)extra space.
Things to watch for
Counting All Characters
A frequent mistake is incrementing or decrementing the depth counter for every character in the string. The string may contain digits, operators, and other characters that should be ignored. Only parentheses ( and ) affect the nesting depth.
Updating Maximum at the Wrong Time
When using a counter approach, the maximum depth should be updated after incrementing for (, not after decrementing for ). Updating after processing ) will miss the peak depth that occurred when the matching ( was processed.
Python code example
class Solution:
def maxDepth(self, s: str) -> int:
res = 0
cur = 0
for c in s:
if c == "(":
cur += 1
elif c == ")":
cur -= 1
res = max(res, cur)
return res
C++ code example
class Solution {
public:
int maxDepth(string s) {
int res = 0, cur = 0;
for (char c : s) {
if (c == '(') {
cur++;
} else if (c == ')') {
cur--;
}
res = max(res, cur);
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.