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-9 and characters '+', '-', '*', '/', '(', ')'
  • s is a valid parentheses string (guaranteed to be properly balanced)

Visualization

Tap to expand
๐Ÿช† Russian Nesting Dolls AnalogyString: ( ( ) ( ) )Step 1: First '(' - Open first doll๐Ÿช†Depth: 1, Max: 1Step 2: Second '(' - Open nested doll๐Ÿช†Depth: 2, Max: 2Step 3: First ')' - Close inner doll๐Ÿช†Depth: 1, Max: 2Step 4: Third '(' - Open new nested doll๐Ÿช†Depth: 2, Max: 2๐ŸŽฏ Key InsightThe maximum number of dolls open simultaneously = Maximum nesting depth!Final Answer: Maximum Depth = 2
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!
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
68.0K Views
Medium Frequency
~8 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen