Skip to content
thesarfo

Reference

Maximum Nesting Depth of Parentheses

Tracking the deepest point in a valid parentheses string using a stack's size at each open paren.

views 0

Given a valid parentheses string, return the maximum nesting depth. "(1+(2*3)+((8)/4))+1"3. "()(())((()()))"3. (LeetCode problem)

Why a stack? The LIFO nature of a stack matches how parentheses nest (the most recently opened must close first). Each push is a deeper level of nesting; each pop returns to a shallower level.

Approach: initialize an empty stack and maxDepth = 0. On '(', push and update maxDepth with the current stack size. On ')', pop. Return maxDepth.

import java.util.Stack;
public class MaximumNestingDepth {
public static int maxDepthUsingStack(String s) {
Stack<Character> stack = new Stack<>();
int maxDepth = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(c); // Push on '('
maxDepth = Math.max(maxDepth, stack.size()); // Update max depth
} else if (c == ')') {
stack.pop(); // Pop on ')'
}
}
return maxDepth;
}
}

Time: O(n). Space: O(n) in the worst case (a string of all ().