easyStack / QueuePure DSA~12 min
Balanced Bracket Depth
A formula editor colour-codes nested parentheses by depth. Given a valid expression string, report the deepest level of nesting so the renderer knows how many colours to cycle through.
Problem
Given a string s containing a valid parenthesisation (and other characters), return the maximum nesting depth of the parentheses.
Input
A string s of length n (1 ≤ n ≤ 10^5); parentheses in s are balanced.
Output
A single integer — the maximum nesting depth.
Constraints
- 1 ≤ n ≤ 100,000
- Parentheses are guaranteed balanced
- Non-parenthesis characters are ignored
Examples
Example 1
Input
s = "(1+(2*3)+((8)/4))+1"
Output
3
The innermost (8) sits three levels deep.
Example 2
Input
s = "(1)+((2))+(((3)))"
Output
3
The deepest group (((3))) reaches depth 3.