Problem summary: Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack
Example 1
"(1+(2*3)+((8)/4))+1"
Example 2
"(1)+((2))+(((3)))"
Example 3
"()(())((()()))"
Related Problems
Maximum Nesting Depth of Two Valid Parentheses Strings (maximum-nesting-depth-of-two-valid-parentheses-strings)
Step 02
Core Insight
What unlocks the optimal approach
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1614: Maximum Nesting Depth of the Parentheses
class Solution {
public int maxDepth(String s) {
int ans = 0, d = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(') {
ans = Math.max(ans, ++d);
} else if (c == ')') {
--d;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1614: Maximum Nesting Depth of the Parentheses
func maxDepth(s string) (ans int) {
d := 0
for _, c := range s {
if c == '(' {
d++
ans = max(ans, d)
} else if c == ')' {
d--
}
}
return
}
# Accepted solution for LeetCode #1614: Maximum Nesting Depth of the Parentheses
class Solution:
def maxDepth(self, s: str) -> int:
ans = d = 0
for c in s:
if c == '(':
d += 1
ans = max(ans, d)
elif c == ')':
d -= 1
return ans
// Accepted solution for LeetCode #1614: Maximum Nesting Depth of the Parentheses
struct Solution;
impl Solution {
fn max_depth(s: String) -> i32 {
let mut res = 0;
let mut left = 0;
for c in s.chars() {
if c == '(' {
left += 1;
}
if c == ')' {
left -= 1;
}
res = res.max(left);
}
res
}
}
#[test]
fn test() {
let s = "(1+(2*3)+((8)/4))+1".to_string();
let res = 3;
assert_eq!(Solution::max_depth(s), res);
let s = "(1)+((2))+(((3)))".to_string();
let res = 3;
assert_eq!(Solution::max_depth(s), res);
let s = "1+(2*3)/(2-1)".to_string();
let res = 1;
assert_eq!(Solution::max_depth(s), res);
let s = "1".to_string();
let res = 0;
assert_eq!(Solution::max_depth(s), res);
}
// Accepted solution for LeetCode #1614: Maximum Nesting Depth of the Parentheses
function maxDepth(s: string): number {
let ans = 0;
let d = 0;
for (const c of s) {
if (c === '(') {
ans = Math.max(ans, ++d);
} else if (c === ')') {
--d;
}
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.