Suppose we have N natural numbers in a queue. ex queue = [3, 14, 1, 20] and an empty stack
We are allowed to make only two actions:
- Action "x": Dequeue an element from the queue and push it to the stack.
- Action "o": Pop an element from the stack and enqueue it in the queue.
In the above example, the following actions sort the queue in ascending order:
Actions: "xxoxooxxoo"
ex.
- queue: 3, 14, 1, 20 stack:
- x
- queue: 14, 1, 20 stack: 3
- x
- queue: 1, 20 stack: 14, 3
- o
- queue: 1, 20, 14 stack: 3
- x
- queue: 20, 14 stack: 1, 3
- o
- queue: 20, 14, 1 stack: 3
- o
- queue: 20, 14, 1, 3 stack:
- x
- queue: 14, 1, 3 stack: 20
- x
- queue: 1, 3 stack: 14, 20
- o
- queue: 1, 3, 14 stack: 20
- o
- queue: 1, 3, 14, 20 stack:
and the queue is sorted.
Any idea how can I solve this problem with the minimum number of actions?
[EDIT]
Actually, it should be with a minimum number of steps, as there is a dummy solution:
You can just rotate the queue by actions: "xo" (move the first number to the end of the queue) and when you reach the largest number, push it to the stack. Repeat this process until the queue is empty. The stack now contains all the numbers with the top being the smallest number. So you just push them out one by one and you have a sorted queue.