← DiffPush

Implement Queue using Stacks

Baseline Stack and Queues · Learning O(1) amortized per operation · O(n)

The Two-Drawer Mail Sorter

A mailroom sorts envelopes with two stacking drawers. Letters arrive at the in-drawer on top of each other, but deliveries must leave in arrival order — so whenever the out-drawer is empty, the clerk pours the entire in-drawer into it, flipping the order so the oldest letter surfaces first. Implement this sorter: arrivals always land in the in-drawer, and departures drain the out-drawer.

Input: A list of operations, each either ["enqueue", value] to insert or ["dequeue"] to remove.

Output: Return the list of values produced by every dequeue operation, in order; a dequeue on an empty structure yields -1.

Constraints

Examples

Example 1

Input: {"operations":[["enqueue",1],["enqueue",2],["dequeue"],["enqueue",3],["dequeue"],["dequeue"]]}
Output: [1,2,3]
Pure FIFO behavior: 1 leaves first even though it sits at the bottom of the in-stack.

Example 2

Input: {"operations":[["enqueue",9],["dequeue"],["dequeue"]]}
Output: [9,-1]
One letter is delivered, then the next request finds both drawers empty.

Solve this in your browser →

Also on LeetCode ↗