Data Structures & AlgorithmsVery hardTCS Digital · Product companies

The numbers 1, 2, 3, 4, 5 are pushed onto an initially empty stack in this order, and pops may be interleaved with pushes at any time. Which of the following output sequences cannot be produced?

  1. A. 3 2 5 4 1
  2. B. 4 5 3 2 1
  3. C. 2 3 5 4 1
  4. D. 3 4 1 5 2

Correct answer: D. 3 4 1 5 2

After popping 3 and 4, the stack holds 1 and 2 with 2 on top, so 2 must be popped before 1. The sequence 3 4 1 ... asks for 1 first, which is impossible; the other three sequences can be generated.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic