Drill

ProblemsPython › patterns

How deep does this nest

easypatternsStacksStringsPython

A config linter reports the deepest level of nested parentheses in an expression, because past a certain depth nobody can read it.

deepest_nesting(expression: string) → int

Solve it in the editor →

Where you start

def deepest_nesting(expression: str) -> int:
    

Worked examples

CallResult
deepest_nesting("(1+(2*3)+((8)/4))+1")3
deepest_nesting("(1)+((2))+(((3)))")3
deepest_nesting("1+2")0
deepest_nesting("")0

Hint

You do not need to store anything — a counter that rises on an opener and falls on a closer is a stack whose only interesting property is its height.

Reference solution in Python
def deepest_nesting(expression: str) -> int:
    depth = 0
    deepest = 0
    for ch in expression:
        if ch == "(":
            depth += 1
            deepest = max(deepest, depth)
        elif ch == ")":
            depth -= 1
    return deepest

The same problem in another language

More patterns problems in Python