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
Maximum Nesting Depth of Parentheses INPUT s = "(1+(2*3)+((8)/4))+1" Nesting Visualization: Depth 0: outer level Depth 1: (1+(2*3)+((8)/4)) Depth 2: (2*3), ((8)/4) Depth 3: (8) -- MAX String Characters: ( 1 + ( 2 * 3 ) + ( ( 8 ) / 4 ) ) + 1 ( open ) close other ALGORITHM STEPS 1 Initialize Counters depth = 0, maxDepth = 0 2 Iterate Through String Process each character 3 Update Depth Counter '(' : depth++, update max ')' : depth-- 4 Return Maximum Return maxDepth value Trace (key moments): Char depth maxDepth Action (11++ (22++ (33++ MAX (33++ )23-- ...03end FINAL RESULT Maximum Nesting Depth 3 OK - Valid Result Deepest nesting found at: (1+(2*3)+((8)/4))+1 Position: "((8)/4)" inner (8) Depth Breakdown: Level 1: outermost ( ) Level 2: (( )) Level 3: ((( ))) -- MAX Key Insight: The counter-based approach tracks depth by incrementing for '(' and decrementing for ')'. We update maxDepth immediately after incrementing (on '(') to capture the deepest level. Time: O(n), Space: O(1) - optimal single pass solution using only two integer variables. TutorialsPoint - Maximum Nesting Depth of the Parentheses | Counter-Based Solution (Optimal)
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
30.3K Views
Medium Frequency
~10 min Avg. Time
892 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