1614. Maximum Nesting Depth of the Parentheses - Explanation

Problem Link

Description

You are 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 <= 100
  • s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
  • It is guaranteed that parentheses expression s is a VPS.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • String Traversal - Iterating through characters in a string one by one
  • Stack Data Structure - Understanding how stacks work for tracking nested/paired elements
  • Recursion Basics - Using recursive function calls to process sequential data

1. Recursion

Intuition

We can process the string from right to left using recursion. Each open parenthesis increases our depth count, and each close parenthesis decreases it. By tracking the maximum absolute value of this count at any point, we find the deepest nesting level. Processing from right to left means we encounter closing parentheses first, which decrement the counter, and opening parentheses later, which increment it.

Algorithm

  1. Initialize a result variable res to track the maximum depth.
  2. Use recursion starting from index 0. At each step, first recurse to the next index to get the running count.
  3. If the current character is (, increment the count. If it's ), decrement the count.
  4. Update res with the maximum of res and the absolute value of the count.
  5. Return the final result after processing all characters.
class Solution:
    def maxDepth(self, s: str) -> int:
        res = 0

        def dfs(i):
            nonlocal res
            if i == len(s):
                return 0

            cur = dfs(i + 1)
            if s[i] == '(':
                cur += 1
            elif s[i] == ')':
                cur -= 1

            res = max(res, abs(cur))
            return cur

        dfs(0)
        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n) for recursion stack.

2. Stack

Intuition

A stack naturally models nested structures. Each time we see an opening parenthesis, we push it onto the stack, increasing the current depth. Each closing parenthesis pops from the stack, decreasing the depth. The maximum stack size during traversal equals the maximum nesting depth.

Algorithm

  1. Initialize an empty stack and a result variable res = 0.
  2. Iterate through each character in the string.
  3. If the character is (, push it onto the stack and update res with the maximum of res and the current stack size.
  4. If the character is ), pop from the stack.
  5. Return res after processing all characters.
class Solution:
    def maxDepth(self, s: str) -> int:
        res, stack = 0, []

        for c in s:
            if c == "(":
                stack.append(c)
                res = max(res, len(stack))
            elif c == ")":
                stack.pop()

        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

3. Iteration

Intuition

We don't actually need to store the parentheses in a stack. Since we only care about the depth (stack size), we can replace the stack with a simple counter. This reduces space complexity to O(1) while maintaining the same logic.

Algorithm

  1. Initialize res = 0 to track the maximum depth and cur = 0 to track the current depth.
  2. Iterate through each character in the string.
  3. If the character is (, increment cur. If it's ), decrement cur.
  4. After each character, update res with the maximum of res and cur.
  5. Return res.
class Solution:
    def maxDepth(self, s: str) -> int:
        res = 0
        cur = 0

        for c in s:
            if c == "(":
                cur += 1
            elif c == ")":
                cur -= 1
            res = max(res, cur)

        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Common Pitfalls

Counting All Characters

A frequent mistake is incrementing or decrementing the depth counter for every character in the string. The string may contain digits, operators, and other characters that should be ignored. Only parentheses ( and ) affect the nesting depth.

Updating Maximum at the Wrong Time

When using a counter approach, the maximum depth should be updated after incrementing for (, not after decrementing for ). Updating after processing ) will miss the peak depth that occurred when the matching ( was processed.