Code Logo

Maximum Nesting Depth

Published at23 Jul 2026
Easy 0 views
Like0

You are given a valid parentheses string containing only ( and ). Find the maximum nesting depth of the parentheses. The nesting depth is the maximum number of open parentheses at any point in the string.

The depth increases by 1 for each ( and decreases by 1 for each ). Track the current depth as you iterate, and record the maximum depth seen. This is a simple counter that naturally models stack behavior without needing an actual stack data structure.

For example, "(1+(2*3)+((8)/4))+1" has maximum depth 3 because the innermost ((8)) is nested 3 levels deep. "()" has depth 1.

This problem tests understanding of stack operations in a practical context. The stack-based approach is the standard solution and runs in linear time. It is commonly asked in entry-level interviews to assess fundamental data structure knowledge.

Although this problem does not require an explicit stack data structure, it models stack behavior perfectly: each '(' pushes onto an implicit stack and each ')' pops from it. The depth at any point is the size of the implicit stack. This problem is often used as a warm-up before more complex stack problems like Longest Valid Parentheses.

Example Input & Output

Example 1
Input
"(1)+((2))+(((3)))"
Output
3
Explanation

Innermost (((3))) has depth 3.

Example 2
Input
"(1)+(2)+(3)"
Output
1
Explanation

No nesting, max depth 1.

Example 3
Input
""
Output
0
Explanation

Empty string has depth 0.

Algorithm Flow

Recommendation Algorithm Flow for Maximum Nesting Depth
Recommendation Algorithm Flow for Maximum Nesting Depth

Solution Approach

Track current depth and max depth. Iterate: ( increments depth, ) decrements. Update max after increment.

function solution(s) {
  var depth = 0, maxDepth = 0;
  for (var i = 0; i < s.length; i++) {
    if (s[i] === "(") { depth++; maxDepth = Math.max(maxDepth, depth); }
    else if (s[i] === ")") depth--;
  }
  return maxDepth;
}

Time O(n), Space O(1).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(String s) {
        int depth = 0, maxDepth = 0;
        for (char ch : s.toCharArray()) {
            if (ch == '(') { depth++; maxDepth = Math.max(maxDepth, depth); }
            else if (ch == ')') depth--;
        }
        return maxDepth;
    }
}