Data Structures & AlgorithmsHard

A single stack, starting empty, is used to sort the input permutation of 1..4 into 1, 2, 3, 4 at the output (each input element is pushed once and popped at most when it is on top). How many of the 24 permutations of 1, 2, 3, 4 can be sorted this way?

  1. A. 24
  2. B. 14
  3. C. 16
  4. D. 15

Correct answer: B. 14

A permutation is stack-sortable exactly when it avoids the pattern 231, and the count for n is the Catalan number C(n). For n = 4 that gives 14, while the 2^n or n! counts ignore the stack's last-in-first-out restriction.

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

Exams that ask this topic