IAE Academy

GATE 2023 CS Q.59: solution and answer

GATE 2023 · CSQ.59 · 2 marks · NAT

Consider a sequence of elements , , , , , and . The following operations are performed on a stack and a queue , both of which are initially empty.

I: push the elements of from to in that order into .

II: enqueue the elements of from to in that order into .

III: pop an element from .

IV: dequeue an element from .

V: pop an element from .

VI: dequeue an element from .

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

VIII: Repeat operation VII three times.

IX: pop an element from .

X: pop an element from .

The top element of after executing the above operations is ____ (answer as an integer).

See the question in the paper

Answer and solution

ANSWER

The top element of S after executing all operations is 8.

Official answer: 8Source: Official answer key, GATE 2023 CS (IIT Kanpur)

  1. Push into in order: (bottom→top) .

  2. Enqueue into in order: (front→back) .

  3. III: pop removes ; .

  4. IV: dequeue removes ; .

  5. V: pop removes ; .

  6. VI: dequeue removes ; .

  7. VII: dequeue removes , push onto ; ; .

  8. VIII (repeat VII three more times): dequeue → push (; ); dequeue → push (; ); dequeue → push (; ).

  9. IX: pop removes ; (top ).

  10. X: pop removes ; (top ).

KEY IDEA

Simulate the stack and queue step by step exactly in the order the operations are listed, tracking the full contents (not just the top/front) so each subsequent pop/dequeue references the correct element.

WATCH OUT FOR

Losing track of the moving front of Q while three separate dequeue-and-push actions happen in operation VIII (mixing up which element is currently at the front of Q), or forgetting that operation III pops before operation IV dequeues, so mis-ordering the interleaving of pops/dequeues against pushes/enqueues.

From the GATE 2023 CS paper. Every question of this paper · Download the full paper · All 13 Linear structures questions, with notes

More Linear structures questions