Editor

Queue From Two Stacks

#63 · Stacks and queues · Intermediate · 60 XP · about 12 min

A queue serves items in the order they arrived, while a stack serves the newest item first. Build a class StackQueue that behaves like a queue but keeps its items in two Python lists used only as stacks: add with append, remove with pop() from the end, look at the last item and check the length.

  • enqueue(x) adds x at the back of the queue.
  • dequeue() removes the item at the front and returns it.
  • peek() returns the item at the front without removing it.
  • size() returns how many items are waiting.
  • is_empty() returns True when the queue holds nothing.

Over a long run of calls, each call should take constant time on average.

Examples

q = StackQueue()
q.enqueue("a")
q.enqueue("b")
q.enqueue("c")
q.dequeue()   # returns 'a'
q.peek()      # returns 'b'
q.enqueue("d")
q.size()      # returns 3
q.is_empty()  # returns False

Constraints

  • Up to 100,000 calls in total.
  • dequeue and peek are only called when the queue is not empty.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.