The GATE Grind

GATE 2023 CS – Question 59

Programming and Data Structures · Stacks and Queues · 2 marks · Numerical answer

Consider a sequence a of elements $a_0 = 1, a_1 = 5, a_2 = 7, a_3 = 8, a_4 = 9$, and $a_5 = 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 $a_0$ to $a_5$ in that order into S. II: enqueue the elements of a from $a_0$ to $a_5$ 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 ______.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 8

Explanation

After III and V, S = [1,5,7,8] and Q loses 1 and 5, leaving [7,8,9,2]. VII plus its three repeats moves 7,8,9,2 onto S, giving [1,5,7,8,7,8,9,2]. IX and X pop 2 and 9, so the top is 8.