Consider a sequence a of elements a0 = 1, a1 = 5, a2 = 7, a3 = 8, a4 = 9, and…

2023

Consider a sequence a of elements a0 = 1, a1 = 5, a2 = 7, a3 = 8, a4 = 9, and a5 = 2. The following operations are performed on a stack S and a queue Q, both of which are initially empty.

    I: push the elements of a from a0 to a5 in that order into S.

    II: enqueue the elements of a from a0 to a5 in that order into Q.

    III: pop an element from S.

    IV: dequeue an element from Q.

    V: pop an element from S.

    VI: dequeue an element from Q.

    VII: dequeue an element from Q and push the same element into S.

    VIII: Repeat operation VII three times.

    IX: pop an element from S.

    X: pop an element from S.

The top element of S after executing the above operations is .

Attempted by 157 students.

Show answer & explanation

Correct answer: 8

Key idea: simulate the stack (LIFO) and queue (FIFO) step by step.

  • After pushing all elements into the stack and enqueuing into the queue: Stack (top→bottom): 2, 9, 8, 7, 5, 1; Queue (front→rear): 1, 5, 7, 8, 9, 2.

  • After the next two pops from the stack and two dequeues from the queue: pop removes 2 then 9 → Stack: 8, 7, 5, 1; dequeue removes 1 then 5 → Queue: 7, 8, 9, 2.

  • Performing the dequeue-and-push operation once and then repeating it three more times (as stated) moves 7, 8, 9, 2 from the front of the queue onto the stack in that order.

  • After those four transfers, Stack (top→bottom): 2, 9, 8, 7, 8, 7, 5, 1; Queue: empty.

  • Two final pops remove 2 then 9, leaving the top element of the stack as 8.

Final answer: 8

Explore the full course: Gate Guidance By Sanchit Sir