ProgrammingHardTCS NQT · Accenture

The procedure below checks the bracket string "(()())" and prints the maximum nesting depth it reaches. The depth is raised by '(' and lowered by ')'. What is printed?

The procedure below checks the bracket string "(()())" and prints the maximum nesting depth it reaches. The depth is raised by '(' and lowered by ')'. What is printed?
depth = 0; best = 0
for each character ch
    depth = depth + 1 for '(' and depth = depth - 1 for ')'
    best = max(best, depth)
end for
Print best
  1. A. 3
  2. B. 6
  3. C. 0
  4. D. 2

Correct answer: D. 2

The depth goes 1, 2, 1, 2, 1, 0, so the maximum is 2. Counting the opening brackets gives 3, the length is 6, and the final depth after the scan is 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic