Exercise · Volume 1 · 2.2.1-14
Exercise 2.2.1-14
not stated yet in Lean solution written
| Rating | 26 |
|---|---|
| Kind | K5, design an algorithm: give a method for a task, often with a cost bound from the written solution |
| Section | Section 2.2.1 of Volume 1 |
The task
Only stacks are allowed as data structures. Show how to build a queue from two stacks so that the work per operation is small on average.
The exact wording is in your copy of the book.
Hints
Open one hint at a time. Try the exercise again after each.
Hint 1
One stack holds the new items, with the newest on top. The oldest item is then at the bottom of this stack, which you cannot reach.
Hint 2
Pour the whole first stack into a second stack. What happens to the order?
Solution
Show the solution
Plan. Keep an input stack and an output stack. Move items from the first to the second only when the second is empty. Count the moves to show a constant average cost.
Let be the input stack and the output stack. The queue holds, from the front to the rear, the items of from the top to the bottom, followed by the items of from the bottom to the top.
Insert at the rear. Push on .
Remove the front item. If is empty, pop each item of and push it on until is empty. This reverses the order, so the oldest item of the queue is now on top of . Then pop and return the item. If and are both empty, the queue is empty, and the removal is an underflow.
Why it is right. The rule keeps the order stated above. An insert adds on top of , which is the rear. A pour moves the whole of onto an empty , and it reverses the block, so the block reads from the front to the rear when read from the top of down. A removal takes the top of , which is the front.
Cost. One pour of items costs pops and pushes, so one removal can cost a long time. But an item is pushed on once, popped from once, pushed on once, and popped from once, and never moves back. So operations cost at most stack steps in all. The average cost of an operation is at most stack steps.
Check
I ran the structure against a built-in double-ended queue on random operations, with about percent inserts. Every removal returned the same item in both. The pour moved items in all, which is below the bound of one move per inserted item.
Remarks
The cost per operation is constant on average, but a single removal can take a time proportional to the length of the queue. If a worst-case bound is needed, the pour must be spread over several operations, and this makes the method more complex. The book's answer uses the same two stacks with the roles of the stacks written in the other order.
This solution is drafted, and a person has not reviewed it yet. The source.
In Lean
not stated yet The exercise is not stated in Lean yet.
The status is computed from the Lean build. The node of the map.
Something is wrong? Report it.