Data Structures & AlgorithmsHard

The numbers 1, 2, 3, 4, 5 are pushed onto an initially empty stack in this order, and a pop may be performed whenever the stack is non-empty. How many DIFFERENT output sequences (order in which elements leave) are possible?

  1. A. 120
  2. B. 32
  3. C. 42
  4. D. 14

Correct answer: C. 42

Each output is a stack-permutation, and the count of distinct ones for n elements is the Catalan number C(n) = (2n)!/((n+1)!·n!). For n = 5 that gives 42, while the unrestricted 5! = 120 and the power-of-two count ignore the stack discipline.

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

Exams that ask this topic