Maximum Nesting Depth of the Parentheses - Problem
Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
A valid parentheses string is a string consisting only of '(' and ')' characters where every opening parenthesis has a corresponding closing parenthesis.
Example: In the string "(1+(2*3)+((8)/4))+1", the maximum nesting depth is 3 because at one point we have three levels of nested parentheses: (((.
Input & Output
Example 1 — Mathematical Expression
$
Input:
s = "(1+(2*3)+((8)/4))+1"
›
Output:
3
💡 Note:
The deepest nesting occurs at "((8)" where we have 3 levels: outer parentheses, plus parentheses, and inner parentheses around 8
Example 2 — Simple Nested
$
Input:
s = "(1)+((2))+(((3)))"
›
Output:
3
💡 Note:
The string (((3))) has maximum nesting depth of 3 levels deep
Example 3 — No Nesting
$
Input:
s = "1+(2*3)-(4/5)"
›
Output:
1
💡 Note:
All parentheses are at the same level with no nesting, so maximum depth is 1
Constraints
- 1 ≤ s.length ≤ 100
- s consists of digits, '+', '-', '*', '/', '(', and ')'
- It is guaranteed that parentheses expression is valid
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Valid parentheses string with other characters
2
Track Depth
Count opening and closing parentheses
3
Maximum Depth
Return the highest nesting level found
Key Takeaway
🎯 Key Insight: Use a simple counter to track current nesting depth in O(1) space
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code