ProgrammingHardTCS NQT · Accenture

For the bracket string "(()(()))", the procedure below tracks the nesting depth and prints the maximum depth reached. What is printed?

For the bracket string "(()(()))", the procedure below tracks the nesting depth and prints the maximum depth reached. What is printed?
depth = 0; best = 0
for each character ch
    if ch == '(' then depth = depth + 1 else depth = depth - 1
    best = max(best, depth)
end for
Print best
  1. A. 3
  2. B. 4
  3. C. 8
  4. D. 0

Correct answer: A. 3

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

More Pseudocode and Code Tracing questions

Exams that ask this topic