Two-Spike Order Rail

EasydesignAlso known as Implement Queue using Stacks

A small diner keeps order tickets on spikes: you push a ticket down onto the spike, and you can only take the ticket on top. A spike is a stack. The cooks, though, must cook orders in the order they came in, oldest first.

The diner has exactly two spikes and nothing else. With a bit of care, the two spikes together can hand out tickets in arrival order.

Your task

Write a class TicketRail with these methods:

  • pin(ticket): a new order arrives with this ticket number.
  • serve(): remove and return the oldest ticket still waiting.
  • peek(): return the oldest ticket without removing it.
  • isEmpty(): return true if no tickets are waiting.

Store tickets only in two stacks, using only push, pop, look at the top, and check if empty (an array with push / pop in JavaScript, a list with append / pop in Python). Each method should take O(1) time on average over many calls.

class TicketRail

Examples

Example 1
Input
new TicketRail()
.pin(12)
.pin(15)
.serve()
.pin(18)
.peek()
.serve()
.serve()
.isEmpty()
Output
[null, null, null, 12, null, 15, 15, 18, true]
Why

Tickets 12 and 15 are pinned. The oldest, 12, is served first. Then 18 arrives. The oldest left is 15, so peek shows 15 and serve hands out 15, then 18. Now the rail is empty.

Constraints

  • 1 ≤ number of method calls ≤ 1,000
  • 1 ≤ ticket ≤ 1,000,000; ticket numbers may repeat.
  • serve and peek are only called when at least one ticket is waiting.
Start with brute force

Use one spike. To serve, lift every ticket off onto the second spike, take the bottom one, then put all the others back.

That moves every waiting ticket twice for every single serve, so with n tickets waiting each serve is O(n), and a busy shift costs O(n²). The better design moves each ticket across at most once in its whole life.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code