1614. Maximum Nesting Depth of the Parentheses
- String
- Stack
TIME
O(n)
SPACE
O(1)
Intuition
Depth at any position is just the number of open brackets to its left minus the number of closed ones, so a single counter tracks it. The answer is the largest value the counter ever reaches. Since the input is guaranteed to be a valid parentheses string, brackets always match up and the counter can never dip below zero, which means an actual stack would only hold redundant information.
Approach
- Keep
depth = 0andbest = 0. - For each character:
(incrementsdepthand updatesbest;)decrementsdepth; anything else is ignored. - Return
best.
Complexity
- Time: O(n)
- Space: O(1)
Edge Cases
- No parentheses at all (
"1+2") → 0 - Flat sequence
"()()()"→ 1, since the groups do not nest - Fully nested
"((((()))))"→ the depth equals the number of open brackets - Mixed flat and nested groups, where the deepest group is not the first (Example 3)
- Digits and operators are irrelevant and only need skipping
- Checking
bestonly on(is enough; depth never peaks anywhere else
Code
class Solution:
def maxDepth(self, s: str) -> int:
"""
1614. Maximum Nesting Depth of the Parentheses
Time: O(n)
Space: O(1)
"""
depth = 0
best = 0
for ch in s:
if ch == "(":
depth += 1
if depth > best:
best = depth
elif ch == ")":
depth -= 1
return best/**
* 1614. Maximum Nesting Depth of the Parentheses
* Time: O(n)
* Space: O(1)
*/
class Solution {
public int maxDepth(String s) {
int depth = 0;
int best = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
depth++;
if (depth > best) {
best = depth;
}
} else if (ch == ')') {
depth--;
}
}
return best;
}
}