Implement a Queue Using Two Stacks

Implement queueOpsFromStacks

Implement a FIFO queueFIFOFirst In, First Out — the earliest-enqueued element is always the first one dequeued, the opposite order from a stack. using only stack operationsStack OperationsPush (add to the top), pop (remove from the top), and peek the top — a stack is LIFO (Last In, First Out). — push onto the top, pop from the top, peek the top — supporting enqueue(v), dequeue(), front(), isEmpty(), and size(). This version takes a fixed sequence of operations and replays them, returning the result of every dequeue, front, isEmpty, and size call as an array. This is the mirror image of building a stack from queues: a stack always hands back its newest element, the opposite of what a queue needs. One fix reorders on every enqueue, keeping the oldest value permanently on top so dequeue and front stay cheap. A better fix defers that reordering: let values pile up cheaply, and only pay the reordering cost when something actually needs to come off the front — and crucially, that cost only recurs once the "read-out" side runs dry, not on every single call. Spread across a whole sequence of operations, each element is only ever moved between the two stacks a constant number of times, giving every operation O(1) time on average even though individual dequeues can occasionally do more work than others.

Example 1:

Input: ops = ["enqueue","enqueue","enqueue","dequeue","dequeue","front"], args = [5,10,15,0,0,0]

Output: [5,10,15]

Example 2:

Input: ops = ["isEmpty","enqueue","isEmpty","dequeue","isEmpty"], args = [0,7,0,0,0]

Output: [1,0,7,1]

Example 3:

Input: ops = ["enqueue","enqueue","size","dequeue","size"], args = [1,2,0,0,0]

Output: [2,1,1]

+ 6 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of operations ≤ 12
  • Each operation is one of enqueue, dequeue, front, isEmpty, or size
  • 0 ≤ enqueued value ≤ 1000
  • dequeue and front return -1 when the queue is empty
  • Only stack operations (push onto the top, pop from the top, peek the top) may be used to store elements
  • This version replays a fixed sequence of operations and reports the result of every dequeue, front, isEmpty, and size call, in order (enqueue has no return value)

ops =

["enqueue", "enqueue", "enqueue", "dequeue", "dequeue", "front"]

args =

[5, 10, 15, 0, 0, 0]