MediumPythonJavaScriptTypeScript

Queue via Two Stacks

Data StructuresQueueStack

Implement a FIFO queue using only two stacks (JavaScript arrays limited to
push and pop). No shift, unshift, splice, or index access allowed
on the internal storage.

API

enqueue(value) → void      add to the back
dequeue()      → value | null  remove and return the front; null if empty
peek()         → value | null  front value without removing; null if empty
isEmpty()      → boolean

solve(ops) replays an array of operation tuples and returns the output
of every call in order. enqueue produces null in the output.

solve([
  ['enqueue', 1],
  ['enqueue', 2],
  ['dequeue'],
  ['peek'],
  ['isEmpty'],
])
→ [null, null, 1, 2, false]

Key insight — lazy transfer: move all items from the *inbox* stack to the
*outbox* stack only when the outbox is empty and a dequeue/peek is needed.
This gives amortised O(1) per operation.

Sample tests

Test #1peek never removes — head stays 10 until dequeued
Input: [[["enqueue",10],["peek"],["enqueue",20],["peek"],["dequeue"],["peek"]]]
Output: [null,10,null,10,10,20]
Test #2isEmpty reflects state correctly through the lifecycle
Input: [[["isEmpty"],["enqueue",5],["isEmpty"],["dequeue"],["isEmpty"]]]
Output: [true,null,false,5,true]
Test #3Three enqueues followed by four dequeues (last one empty)
Input: [[["enqueue",1],["enqueue",2],["enqueue",3],["dequeue"],["dequeue"],["dequeue"],["dequeue"]]]
Output: [null,null,null,1,2,3,null]