ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Stack s1 = empty, s2 = empty
Procedure enqueue(Integer x)
    push(s1, x)
End Procedure
Function dequeue()
    if (s2 is empty)
        while (s1 is not empty)
            push(s2, pop(s1))
        end while
    end if
    return pop(s2)
End Function
enqueue(1)
enqueue(2)
enqueue(3)
Integer d1 = dequeue()
enqueue(4)
enqueue(5)
Integer d2 = dequeue()
Print d1, d2, top(s1), top(s2)
  1. A. 1 2 5 3
  2. B. 1 2 3 5
  3. C. 1 4 5 3
  4. D. 3 2 5 3

Correct answer: A. 1 2 5 3

The first dequeue pours 3, 2, 1 into s2 (1 on top) and returns 1. 4 and 5 go onto s1. s2 is not empty, so the second dequeue just pops 2. Now top(s1) = 5 and top(s2) = 3: 1 2 5 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic