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)- A. 1 2 5 3
- B. 1 2 3 5
- C. 1 4 5 3
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (^ is bitwise XOR) Integer s = 0 for (each i from 0 to 15) s = s + (i ^ 5) end for…
- What will be the output of the following pseudocode? (parameters are passed by value; inside g, x is the global x; operands are evaluated…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division; + joins strings) Function…
- What is the time complexity of the following pseudocode, as a function of n? i = n while (i > 1) j = i while (j < n) j = j 2 end while i =…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer c = 0, i = 1, j while…
- What will be the output of the following pseudocode? (stop ends the program; code(c) gives a letter's character code) String s =…