← All solutions
September 28Easy

Maximum nesting depth of the parentheses

  • String
  • Stack
  • Bracket Sequences

Problem

Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.

Solution

class Solution:
    def maxDepth(self, s: str) -> int:
        opened = 0
        max_depth = 0
        for char in s:
            if char == "(":
                opened += 1
                max_depth = max(max_depth, opened)
            elif char == ")":
                opened -= 1
        return max_depth