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
Innermost (((3))) has depth 3.
No nesting, max depth 1.
Empty string has depth 0.
Algorithm Flow

Solution Approach
Track current depth and max depth. Iterate: ( increments depth, ) decrements. Update max after increment.
Time O(n), Space O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
