Drill

ProblemsC++ › patterns

How deep does this nest

easypatternsStacksStringsC++

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

deepestNesting(expression: string) → int

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int deepestNesting(std::string expression) {
    
}

Worked examples

CallResult
deepestNesting(std::string("(1+(2*3)+((8)/4))+1"))3
deepestNesting(std::string("(1)+((2))+(((3)))"))3
deepestNesting(std::string("1+2"))0
deepestNesting(std::string(""))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 C++
int deepestNesting(std::string expression) {
    int depth = 0, deepest = 0;
    for (char ch : expression) {
        if (ch == '(') {
            depth++;
            if (depth > deepest) deepest = depth;
        } else if (ch == ')') {
            depth--;
        }
    }
    return deepest;
}

The same problem in another language

More patterns problems in C++