Maximum Nesting Depth

Medium · rating 1300 · stack, strings

A configuration string uses the brackets {} and []. Read one line and print the maximum nesting depth of brackets. The brackets are guaranteed to be balanced; a string with no brackets has depth 0.

Editorial

Maximum Nesting Depth reports how deeply brackets nest. Track a running depth: increment on each opening bracket, decrement on each closing one, and record the peak.

depth = peak = 0
for c in s:
    if c in '([{':
        depth += 1; peak = max(peak, depth)
    elif c in ')]}':
        depth -= 1
print(peak)

Complexity

Time: O(n). Space: O(1) — no stack is needed when you only want the depth.

Open Maximum Nesting Depth in Code Arena →