← All Exercises

Queue Using Two Stacks

intermediatejavascript~25min

Background

This classic problem tests understanding of amortized analysis and the relationship between LIFO and FIFO structures.

Problem

Write a Queue class that implements FIFO ordering using two stacks internally, with efficient amortized dequeue operations.

Input

No input; the queue is initialized empty with two internal stacks.

Output

A Queue instance with enqueue and dequeue methods following FIFO order.

Sample tests

Sample 1

Input: enqueue(1), enqueue(2), dequeue()
Expected: 1

Your solution

Learning objective

Understand amortized time complexity and the stack-to-queue transformation technique.