Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate permutation using a single stack

Can anyone please explain algorithm to generate the permutations possible when using only a single stack and push and pop are the only operations allowed. Have searched about it a lot, but no definite answer. Also the total number of such permutations is given by catalan numbers. But I fail to get a proof for that. Kindly explain that as well if possible.

Thanks!!

like image 306
Rohit Jain Avatar asked Jun 25 '11 18:06

Rohit Jain


People also ask

How do you find the permutation of a stack?

Stack Permutation Using StackContinuously pop elements from the input queue and check if it is equal to the top of output queue or not, if it is not equal to the top of output queue then we will push the element to stack.

How many stack permutations are possible?

The 312-avoiding permutations are also the inverses of the 231-avoiding permutations, and have been called the stack-realizable permutations as they are the permutations that can be formed from the identity permutation by a sequence of push-from-input and pop-to-output operations on a stack.

What is valid stack permutation?

An array is said to be a valid stack permutation of the other if and only if after applying some push and pop operations onto the sequence of elements in that array, will result in the other array.


1 Answers

This problem uses an input queue and an output queue as well as a stack.

The operations are "push an item from the input queue onto the stack" and "pop an item from the stack onto the output queue".

                  1 2 3
output  ______   ______  input  
              \ /
        <--+   |   +---
       pop |   |   | push
           |   |   v

             stack

For example, with the input 1 2 3, you can get the output 2 1 3 with the following sequence:

  • push 1 from input to stack
  • push 2 from input to stack
  • pop 2 from stack to output
  • pop 1 from stack to output
  • push 3 from input to stack
  • pop 3 from stack to output

But you'll have a hard time if you try to generate 3 1 2.


How do you generate all the permutations that are possible with these operations? Well, it's trivial to do recursively: in any given state (where the "state" consists of the contents of the input queue, the stack, and the output queue), there are at most two possible operations you can perform (you can push if there is at least one item on the input queue; you can pop if there is at least one item on the stack), which will give you at most two possible new states to explore.

For further detail regarding this problem, and the relationship with Catalan numbers, go and find a copy of Knuth's "The Art of Computer Programming", volume 1 (3rd ed.) - it's discussed in §2.2.1; see exercises 2 - 5 on pp. 242-243 (and a better version of my diagram on p. 240!).

like image 57
Matthew Slattery Avatar answered Sep 27 '22 23:09

Matthew Slattery