data-structures · beginner · ~15 min

Maximum nesting depth

Track a stack depth's high-water mark.

Challenge

Find how deeply round parentheses are nested in a string.

Task

Implement int max_depth(const char *s) that returns the deepest level of nested round parentheses (). Assume the parentheses are balanced.

Input

s: a NUL-terminated string. Only ( and ) affect the depth; other characters are ignored. The parentheses are guaranteed balanced.

Output

int: the maximum nesting depth (0 if there are no parentheses).

Example

"((()))"     ->   3
"()()"       ->   1
"(()(()))"   ->   3
"abc"        ->   0

Edge cases

  • A string with no parentheses returns 0.

Input format

s: a NUL-terminated string with balanced (); other characters ignored.

Output format

int: deepest level of nested parentheses (0 if none).

Constraints

Parentheses are assumed balanced.

Starter code

int max_depth(const char *s) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.