Question

Consider a sequence aa of elements a0=1,a1=5,a2=7,a3=8,a4=9a_0 = 1, a_1 = 5, a_2 = 7, a_3 = 8, a_4 = 9, and a5=2a_5 = 2. The following operations are performed on a stack SS and a queue QQ, both of which are initially empty.

I: push the elements of aa from a0a_0 to a5a_5 in that order into SS.
II: enqueue the elements of aa from a0a_0 to a5a_5 in that order into QQ.
III: pop an element from SS.
IV: dequeue an element from QQ.
V: pop an element from SS.
VI: dequeue an element from QQ.
VII: dequeue an element from QQ and push the same element into SS.
VIII: Repeat operation VII three times.
IX: pop an element from SS.
X: pop an element from SS.

The top element of SS after executing the above operations is _______.

Official answer and solution
Official answer
8
From
Official GATE 2023 answer key

Solution

Simulate step-by-step the stack SS and queue QQ operations.

Given sequence a=[1,5,7,8,9,2]a = [1, 5, 7, 8, 9, 2]:

  • I: Push a0…a5a_0 \dots a_5 into SS: S=[1,5,7,8,9,2]S = [1, 5, 7, 8, 9, 2] (top is 2).
  • II: Enqueue a0…a5a_0 \dots a_5 into QQ: Q=[1,5,7,8,9,2]Q = [1, 5, 7, 8, 9, 2] (front is 1).
  • III: Pop from SS: pops 2   ⟹  S=[1,5,7,8,9]\implies S = [1, 5, 7, 8, 9].
  • IV: Dequeue from QQ: dequeues 1   ⟹  Q=[5,7,8,9,2]\implies Q = [5, 7, 8, 9, 2].
  • V: Pop from SS: pops 9   ⟹  S=[1,5,7,8]\implies S = [1, 5, 7, 8].
  • VI: Dequeue from QQ: dequeues 5   ⟹  Q=[7,8,9,2]\implies Q = [7, 8, 9, 2].
  • VII: Dequeue from QQ and push to SS: dequeues 7, pushes 7   ⟹  S=[1,5,7,8,7],Q=[8,9,2]\implies S = [1, 5, 7, 8, 7], Q = [8, 9, 2].
  • VIII: Repeat VII 3 times:
    • Dequeue 8, push 8   ⟹  S=[1,5,7,8,7,8],Q=[9,2]\implies S = [1, 5, 7, 8, 7, 8], Q = [9, 2].
    • Dequeue 9, push 9   ⟹  S=[1,5,7,8,7,8,9],Q=[2]\implies S = [1, 5, 7, 8, 7, 8, 9], Q = [2].
    • Dequeue 2, push 2   ⟹  S=[1,5,7,8,7,8,9,2],Q=[]\implies S = [1, 5, 7, 8, 7, 8, 9, 2], Q = [].
  • IX: Pop from SS: pops 2   ⟹  S=[1,5,7,8,7,8,9]\implies S = [1, 5, 7, 8, 7, 8, 9].
  • X: Pop from SS: pops 9   ⟹  S=[1,5,7,8,7,8]\implies S = [1, 5, 7, 8, 7, 8].

The top element of SS is now 8.

Final answer

8

Common trap

Losing track of the repeated dequeue-and-push operations in step VIII.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2023 Computer Science and Information Technology (CS)
Question
59 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.