Skip to content
BytePatterns

Two-Stack Queue Operations

EasyStacks & Queues#two-stacks#amortized~15m

Problem

Build a first-in, first-out queue from two stacks, using only push to the top, pop from the top and a read of the top. Process a list of operations: ["push", x] adds x, ["pop"] removes and reports the oldest value, and ["peek"] reports it without removing it. Return the reported values in order, reporting None when pop or peek finds the queue empty. Each operation should cost O(1) amortized time.

Examples

Input:  ops = [["push", 1], ["push", 2], ["peek"], ["pop"],
               ["push", 3], ["pop"], ["pop"]]
Output: [1, 1, 2, 3]
Why:    values leave in the order they arrived
Input:  ops = [["push", 7], ["pop"], ["push", 8], ["push", 9], ["peek"]]
Output: [7, 8]
Why:    after 7 leaves, 8 is the oldest value left
Input:  ops = [["pop"], ["push", 4], ["peek"]]
Output: [None, 4]
Why:    edge case, popping an empty queue reports None

Hints

0 / 3

Stuck on the idea rather than the code? Queue From Two Stacks covers it.