Maximum Nesting Depth of the Parentheses
EasyUpdated: Aug 2, 2025
Practice on:
Problem
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
- It is an empty string
"", or a single character not equal to"("or")", - It can be written as
AB(Aconcatenated withB), whereAandBare VPS's, or - It can be written as
(A), whereAis a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0depth(C) = 0, whereCis a string with a single character not equal to"("or")".depth(A + B) = max(depth(A), depth(B)), whereAandBare VPS's.depth("(" + A + ")") = 1 + depth(A), whereAis a VPS.
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.
Given a VPS represented as string s, return the nesting depth of s.
Examples
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Solution
Method 1 - Using counters
To determine the nesting depth of a valid parentheses string:
- Initialize a counter
current_depthto track the current depth as we traverse the string. - Initialize a variable
max_depthto keep track of the maximum depth encountered. - Iterate through each character in the string:
- Increment
current_depthwhen encountering an opening parenthesis(. - Update
max_depthifcurrent_depthexceeds it. - Decrement
current_depthwhen encountering a closing parenthesis).
- Increment
- Return the
max_depthas the nesting depth of the string.
Code
Java
class Solution {
public int maxDepth(String s) {
int currentDepth = 0;
int maxDepth = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
} else if (c == ')') {
currentDepth--;
}
}
return maxDepth;
}
}
Python
class Solution:
def maxDepth(self, s: str) -> int:
current_depth = 0
max_depth = 0
for c in s:
if c == '(':
current_depth += 1
if current_depth > max_depth:
max_depth = current_depth
elif c == ')':
current_depth -= 1
return max_depth
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the string, since we traverse the string once. - 🧺 Space complexity:
O(1), because we use a fixed amount of additional space regardless of the input size.