GATE / CS ARCHIVE

GATE CSE 2023 / QUESTION 59

GATE CSE 2023 Q59

Data Structures · Stacks & Queues · Full GATE CSE 2023 paper

GATE 2023, Q59 2 marks · NAT
Report issue

Stacks & Queues

Question 59, GATE 2023: Start with empty stack S and queue Q. Push/enqueue 1,5,7,8,9,2 in that order into each. Then pop S, dequeue Q, pop S, dequeue Q. Four times, dequeue Q and push that element into S. Finally pop S twice. What is the remaining top?
Tap to enlarge
Answer & solution

Official answer: 8

Step through it (24 steps)

Write the stack from bottom to top. After the initial pushes it is [1, 5, 7, 8, 9, 2], and the queue front-to-back is [1, 5, 7, 8, 9, 2]. The two pops remove 2 and 9; the two dequeues remove 1 and 5. The stack is then [1, 5, 7, 8] and the queue [7, 8, 9, 2]. Operation VII and its three repetitions append 7, 8, 9, 2 to the stack. The final two pops remove 2 and 9, leaving top element 8.

Teaching detail. Use different ends for the two structures: a stack removes the most recently pushed item, while a queue removes the earliest enqueued one. After the four transfers, the stack bottom-to-top is [1,5,7,8,7,8,9,2] and the queue is empty. Removing its top two entries leaves [1,5,7,8,7,8], whose final entry is 8. Operation VIII says repeat VII three times after its first execution, making four transfers total. Mistaking this for only three transfers changes the trace.

Original paper, page 62 · Answer key