Maximum Nesting Depth of the Parentheses - Problem
Given a valid parentheses string s, find the maximum nesting depth of the parentheses.
The nesting depth is defined as the maximum number of parentheses that are nested within each other at any point in the string. Think of it as counting how many "levels deep" the parentheses go.
Example: In the string "(1+(2*3)+((8)/4))+1", at the deepest point we have ((8) which represents 2 levels of nesting, so the answer is 2.
Your task is to traverse the string and keep track of the current nesting level, updating the maximum depth whenever you encounter a deeper level of nesting.
Input & Output
example_1.py โ Python
$
Input:
s = "(1+(2*3)+((8)/4))+1"
โบ
Output:
3
๐ก Note:
The string has nested parentheses. At the deepest point ((8), we have 3 levels: the outermost (, then the ( before (, then the ( before 8. So the maximum nesting depth is 3.
example_2.py โ Python
$
Input:
s = "(1)+((2))+(((3)))"
โบ
Output:
3
๐ก Note:
The deepest nesting occurs in (((3))) where we have 3 levels of parentheses nested within each other.
example_3.py โ Python
$
Input:
s = "1+(2*3)/(2-1)"
โบ
Output:
1
๐ก Note:
The parentheses (2*3) and (2-1) are at the same level with no nesting, so the maximum depth is 1.
Constraints
- 1 โค s.length โค 100
-
s consists of digits
0-9and characters'+', '-', '*', '/', '(', ')' - s is a valid parentheses string (guaranteed to be properly balanced)
Visualization
Tap to expand
Understanding the Visualization
1
Start with no dolls
current_depth = 0, max_depth = 0
2
Open dolls for '('
Increment depth, update maximum if needed
3
Close dolls for ')'
Decrement current depth
4
Track maximum
Remember the most dolls ever open simultaneously
Key Takeaway
๐ฏ Key Insight: We only need to track the current nesting level and remember the maximum depth reached - no need to store previous states or use complex data structures!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code