progress

~/problems / Stacks / Stacks

Implement Queue Using Stacks

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

An old printer's firmware only offers stacks, but jobs must print in arrival order. Build StackQueue with push(x), pop() (remove and return the front), peek() (return the front) and is_empty(). pop and peek only run on a non-empty queue.

Use Python lists only as stacks: append, pop(), [-1] and len. No pop(0), insert, middle indexing or deque.

q = StackQueue()
q.push(1)
q.push(2)
q.peek()      # 1
q.pop()       # 1
q.push(3)
q.pop()       # 2
q.is_empty()  # False
q.pop()       # 3
q.is_empty()  # True

⭐ Bonus: a speed test (4 * 10^5 calls) earns a star for amortized O(1) per call: a single call may move many items, but averaged over all calls each one is O(1).

Show hint

pouring one stack into another reverses it. If you only pour when the second runs dry, how often can a job move?

Topic: Stacks. Matching pairs, undo history and evaluating expressions with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc