Solution
ID: past-exam-of-the-computer-science-course-of-the-university-of-oxford/2015/advanced-data-structures-and-algorithms/1/d/solution
Past exam of the computer science course of the University of Oxford 2015 Advanced data structures and algorithms 1 d Solution by
Codex 0 2026-10-31
Use two permanent stacks, and , and one temporary stack, . At operation boundaries is empty. Maintain the representation invariant that the deque, read from front to back, is the top-to-bottom contents of followed by the bottom-to-top contents of . Thus the tops of and are the two accessible ends. Maintain their sizes using two counters, requiring only additional storage in Big O notation.
Adding at the front pushes onto ; adding at the back pushes onto . Removing at an end whose permanent stack is nonempty simply pops that stack. If both permanent stacks are empty, report an empty deque.
- Move the top elements of onto .
- Move all remaining elements of onto .
- Move all elements of back onto .
- Pop and return the top of .
The parked elements are the back half of the deque; the unparked elements are the front half. Moving the front half onto reverses their stack order and exposes the correct front element. Parking and restoring the back half reverses it twice, preserving its original order in . The temporary stack is empty again. For a back removal with empty, exchange the roles of and throughout. Rebalance approximately half the elements, so both ends retain accessible elements after a large transfer.
For the amortized analysis, count each push or pop as one unit and use the potential method withInitially the deque is empty, so , and is always nonnegative. An ordinary insertion or removal costs one unit and changes the size difference by at most one, giving amortized cost at most .
For a rebalancing removal, let . The parked half makes two transfers per element and the other half makes one; each transfer is a pop and a push. Including the final removal, the actual cost isBefore rebalancing the absolute size difference is . Immediately after the split it is at most , and after the removal it is at most . HenceSize tests and counter updates change only these constants. Summing the amortized costs and using nonnegative final potential proves amortized running time for all four operations, with three stacks and additional storage. An individual rebalancing operation can still take linear time in the current size.
New to topics? Read the docs here!