Maximum Nesting Depth of the Parentheses Problem
#1614
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1614.
Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation:
Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Explanation:
Digit 3 is inside of 3 nested parentheses in the string.
Example 3:
Input: s = "()(())((()()))"
Output: 3
Constraints:
1 <= s.length <= 100sconsists of digits0-9and characters'+','-','*','/','(', and')'.- It is guaranteed that parentheses expression
sis a VPS.
Solution
Approach: Count Open Parentheses
The nesting depth at any point of the string is the number of ( that are open there. Scan the string with a counter depth:
(: increasedepthand update the answer with it.): decreasedepth.- Digits and operators do not change the depth.
The string is guaranteed to be valid, so depth never goes negative and we don't need a stack. A string without parentheses has depth 0.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxDepth(self, s: str) -> int:
ans = depth = 0 # depth = number of currently open parentheses
for c in s:
if c == "(":
depth += 1
ans = max(ans, depth)
elif c == ")":
depth -= 1
return ans