Drill

ProblemsTypeScript › patterns

How deep does this nest

easypatternsStacksStringsTypeScript

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

Solve it in the editor →

Where you start

function deepestNesting(expression: string): number {
  
}

Worked examples

CallResult
deepestNesting("(1+(2*3)+((8)/4))+1")3
deepestNesting("(1)+((2))+(((3)))")3
deepestNesting("1+2")0
deepestNesting("")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 TypeScript
function deepestNesting(expression: string): number {
  let depth = 0;
  let deepest = 0;
  for (const ch of expression) {
    if (ch === "(") {
      depth += 1;
      if (depth > deepest) deepest = depth;
    } else if (ch === ")") {
      depth -= 1;
    }
  }
  return deepest;
}

The same problem in another language

More patterns problems in TypeScript