Python coding

Queue built from two stacks

Write a class StackQueue: a first-in, first-out queue of integers whose only storage is stacks, that is, Python lists used through append, pop() from the end, [-1] and len.

  • push(x) adds x at the back of the queue.
  • pop() removes the value at the front and returns it.
  • peek() returns the value at the front without removing it.
  • empty() returns whether the queue holds no values.

pop and peek are never called on an empty queue. Every operation must take O(1) amortized time.

The tests call the provided run_queue(ops): it applies each operation in order and returns the list of results (None for push, shown as null).

Besides the tests, one large input (3,000 queued values, 3,000 pops) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • run_queue([["push",1],["push",2],["peek"],["pop"],["empty"],["pop"],["empty"]]) → [null,null,1,1,false,2,true]
  • run_queue([["push",5],["push",6],["pop"],["push",7],["push",8],["pop"],["pop"],["peek"]]) → [null,null,5,null,null,6,7,8]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A stack hands values back newest first. Pour one stack into another and the order flips, so the oldest value ends up on top.

Hint 2

Keep inbox for pushes and outbox for pops. Pour inbox into outbox only when outbox is empty; pouring earlier lets newer values jump ahead of older ones.

Hint 3

Each value moves at most once, from inbox to outbox, so n operations cost O(n) in total even though one pour can take O(n).

Solution and why it works
pythonO(1) amortized per operation · O(n)
# --- your code ---
class StackQueue:
    def __init__(self):
        self.inbox = []                  # newest value on top
        self.outbox = []                 # oldest value on top

    def push(self, x: int) -> None:
        self.inbox.append(x)

    def pop(self) -> int:
        self.peek()                      # make sure the oldest value is on top of outbox
        return self.outbox.pop()

    def peek(self) -> int:
        if not self.outbox:              # refill only when empty, or newer values jump ahead
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox[-1]

    def empty(self) -> bool:
        return not self.inbox and not self.outbox


# --- provided: do not edit ---
def run_queue(ops: list[list]) -> list:
    queue = StackQueue()
    return [getattr(queue, name)(*args) for name, *args in ops]

One stack reverses order; two reversals restore it. inbox takes every push, and outbox serves the front from its top. When outbox runs dry, pouring all of inbox into it puts the oldest value on top. Each value is pushed and popped at most twice in its life, so the cost is O(1) amortized even though a single pour is O(n). The traps: pouring while outbox still holds values (newer values jump the line), or pouring everything back after each operation, which makes every one O(n).