AlgoPrecision

Stacks And Queues

Queue Operations

Visualize FIFO behavior with enqueue, dequeue, and peek operations before moving into sliding window and scheduling patterns.

Amortized O(1) per operation
FIFO: first in, first outoperation: twoStacksresult: in: [] | out: []
FrontRear
empty queue

Time

Amortized O(1)

Space

O(n)

Step Note

Use one stack for enqueue and one stack for dequeue.

Details
class QueueUsingStacks {
  input = []
  output = []
  enqueue(value: number) {
    this.input.push(value)
  }
  dequeue() {
    if (this.output.length === 0) {
      while (this.input.length) this.output.push(this.input.pop())
    }
    return this.output.pop()
  }
}