AlgoInsight

DSA problem

Implement Stack using Queues

EasyData Structure DesignPattern: Data Structure Designtop600MicrosoftAmazonBloombergAppleAdobe

Implement a last-in-first-out (LIFO) stack using only one queue. The implemented stack should support all the functions of a normal stack: push, top, pop, and empty. You may use only the standard queue operations — push to back, peek/pop from front, size, and is-empty.

MyStack() initializes the empty stack. push(x) pushes element x to the top of the stack. pop() removes the element on the top of the stack and returns it. top() returns the element on the top of the stack. empty() returns true if the stack is empty, false otherwise.

The elegant single-queue trick makes push expensive while keeping pop and top O(1). On push(x), first enqueue x at the tail. Then rotate the queue size - 1 times by repeatedly dequeuing the front and enqueuing it back at the tail. After this rotation, the freshly pushed x sits at the very front of the queue, exactly where the next pop/top will read it. Every previously pushed element shifts back by one position relative to the front.

This gives push an O(n) cost (with n the current size) and pop/top/empty an O(1) cost — a different cost profile than the two-queue variant but using only one queue total. The two-queue alternative makes pop expensive and push cheap; pick the variant that suits the workload.

Examples

Example 1
Input: ["MyStack","push","push","top","pop","empty"] [[],[1],[2],[],[],[]]
Output: [null,null,null,2,2,false]
Explanation: push(1): queue=[1]. push(2): enqueue 2 to get [1,2], then rotate once to get [2,1]. top() returns 2. pop() removes 2, leaving [1]. empty() returns false.
Example 2
Input: ["MyStack","push","push","push","pop","top"] [[],[1],[2],[3],[],[]]
Output: [null,null,null,null,3,2]
Explanation: After three pushes the queue is [3,2,1]. pop() returns 3 and removes it; top() returns 2.
Example 3
Input: ["MyStack","push","pop","empty"] [[],[7],[],[]]
Output: [null,null,7,true]
Explanation: push(7) leaves queue=[7]. pop() returns 7. The stack is empty.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackdesignqueue

Browse all DSA problems