Data Structures & AlgorithmsModerateTCS NQT · stack basics

Problem: What is the maximum nesting depth of parentheses in '(1+(23)+((8)/4))+1'? Run the code.

Problem: What is the maximum nesting depth of parentheses in '(1+(2*3)+((8)/4))+1'? Run the code.
s = '(1+(2*3)+((8)/4))+1'
depth = best = 0
for c in s:
    if c == '(':
        depth += 1
        best = max(best, depth)
    elif c == ')':
        depth -= 1
print(best)
What is printed?
  1. A. 2
  2. B. 4
  3. C. 1
  4. D. 3

Correct answer: D. 3

The deepest point is inside ((8)/4), which sits within the outer bracket, giving depth 3.

More Coding Interview Problems questions

Exams that ask this topic