GATE Computer ScienceVery hardGATE CS (PYQ pattern)

The integers 1 to 6 are pushed in this order onto a stack that can hold at most 2 elements at any moment; pops may be interleaved with pushes at any time, and every number is eventually popped. How many different output sequences are possible?

  1. A. 32
  2. B. 132
  3. C. 89
  4. D. 21

Correct answer: A. 32

Write a push as U and a pop as D. Each output sequence corresponds to exactly one push/pop word of length 12 that never goes below zero and, here, never above height 2. Such a word splits into returns to height 0; each block is U (UD)^m D with m >= 0, so a block of semilength j is unique, and the words are the compositions of 6: 2^5 = 32 (brute force agrees). Without the limit the count would be C6 = 132; with capacity 3 it would be 89.

More Programming and Data Structures (GATE) questions

Exams that ask this topic