Two-Spike Order Rail

EasydesignAlso known as Implement Queue using Stacks

A small diner keeps order tickets on spikes. You push a ticket onto a spike and can only take the top one, so a spike is a stack. But the cooks must cook orders oldest first.

The diner has exactly two spikes. Used with care, they 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 onto the second spike, take the bottom one, then put the rest back.

Each serve moves every waiting ticket twice, so with n tickets waiting a serve is O(n) and a busy shift costs O(n²). The better design moves each ticket across at most once.

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