Skip to main content

GATE CSE 2024Data Structures › Stacks, Queues, Linked Lists & ArraysVerified

GATE CSE 2024 PYQ: ​​​​​Let S 1 \mathrm{S} 1 S 1 and S 2 \mathrm{S} 2 S 2 be two stacks. S 1 \mathrm{S} 1 S 1 has capacity of 4…

​​​​​Let S1\mathrm{S} 1 and S2\mathrm{S} 2 be two stacks. S1\mathrm{S} 1 has capacity of 4 elements. S2\mathrm{S} 2 has capacity of 2 elements. S1\text{S1} already has 4 elements: 100,200,300, and 400, whereas S2\text{S2} is empty, as shown below.400(Top)300200100Stack S1Stack S2\underset{\Large{\text{Stack S1}}}{\begin{array}{|l|} \hline 400\text{(Top)} \\\hline 300 \\\hline 200 \\\hline 100 \\\hline \end{array}}\quad \qquad \underset{\Large{\text{Stack S2}}}{\begin{array}{|l|} \hline &&& \\\hline &&& \\\hline \end{array}}

Only the following three operations are available:

  • PushToS2: Pop the top element from S1 and push it on S2.
  • PushToS1: Pop the top element from S2 and push it on S1.
  • GenerateOutput: Pop the top element from S1 and output it to the user.


Note that the pop operation is not allowed on an empty stack and the push operation is not allowed on a full stack.

Which of the following output sequences can be generated by using the above operations?

  1. A
    100,200,400,300
  2. B
    200,300,400,100
    Correct answer
  3. C
    400,200,100,300
    Correct answer
  4. D
    300,200,400,100
    Correct answer

Answer

(B, C, D) 200 , 300 , 400 , 100 200,300,400,100 200 , 300 , 400 , 100; 400 , 200 , 100 , 300 400,200,100,300 400 , 200 , 100 , 300; 300 , 200 , 400 , 100 300,200,400,100 300 , 200 , 400 , 100

Approach

Simulate each proposed output sequence using the three allowed operations, keeping S1 capacity 4 and S2 capacity 2. Since output is possible only from the top of S1, determine whether each required element can be exposed without violating the capacity limits.

The S2 buffer can hold only two elements. This prevents option A because exposing 100 first would require buffering three larger elements. Options B, C, and D each have an explicit valid sequence of allowed operations.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.