ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (strings are indexed from 0)

What will be the output of the following pseudocode? (strings are indexed from 0)
String s = "{[()]}([)]"
Stack st = empty
Integer bad = -1
for (each i from 0 to length(s) - 1)
    if (s[i] is an opening bracket)
        push(st, s[i])
    else if (st is empty OR top(st) does not match s[i])
        bad = i
        break
    else
        pop(st)
    end if
end for
Print bad, size(st)
  1. A. -1 0
  2. B. 9 2
  3. C. 8 2
  4. D. 7 1

Correct answer: C. 8 2

{[()]} is balanced and empties the stack. Then ( and [ are pushed, and the ) at index 8 does not match the [ on top, so bad = 8 with 2 brackets still on the stack: 8 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic