Find maximum nesting depth of parentheses in a string.
Problem Statement
Examples
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Combining the input according to Maximum Nesting Depth of the Parentheses logic yields 3.
Input: s = "(1)+((2))+(((3)))"
Output: 3
Explanation: Combining the input according to Maximum Nesting Depth of the Parentheses logic yields 3.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
The nesting depth corresponds to the maximum number of unmatched opening parentheses at any point in a valid parentheses string. A simple counter tracking the current depth in a single linear scan is optimal.
Step-by-Step Approach
- Initialize
maxD = 0andcurrentD = 0. - For each character
cins: - If
c === "(",currentD++and updatemaxD = Math.max(maxD, currentD). - If
c === ")",currentD--. - Return
maxD.
Optimal Implementation (JavaScript)
function maxDepth(s) {
let maxD = 0, currentD = 0;
for (let c of s) {
if (c === '(') {
currentD++;
if (currentD > maxD) maxD = currentD;
} else if (c === ')') {
currentD--;
}
}
return maxD;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- No parentheses in string: depth is 0.
- Flat parentheses "()()()": depth is 1.
- Deeply nested "(((())))": depth is 4.