Implement Stack using Queues - Problem

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

  • void push(int x) - Pushes element x to the top of the stack
  • int pop() - Removes the element on the top of the stack and returns it
  • int top() - Returns the element on the top of the stack
  • boolean empty() - Returns true if the stack is empty, false otherwise

Notes:

  • You must use only standard operations of a queue: push to back, peek/pop from front, size, and is empty operations
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque as long as you use only a queue's standard operations

Input & Output

Example 1 — Basic Stack Operations
$ Input: operations = ["MyStack", "push", "push", "top", "pop", "empty"], values = [null, 1, 2, null, null, null]
Output: [null, null, null, 2, 2, false]
💡 Note: Create stack, push 1, push 2, top returns 2 (last pushed), pop returns 2, stack not empty (contains 1)
Example 2 — Single Element
$ Input: operations = ["MyStack", "push", "pop", "empty"], values = [null, 5, null, null]
Output: [null, null, 5, true]
💡 Note: Create stack, push 5, pop returns 5, stack is now empty
Example 3 — Multiple Operations
$ Input: operations = ["MyStack", "push", "push", "push", "top", "pop", "top"], values = [null, 1, 2, 3, null, null, null]
Output: [null, null, null, null, 3, 3, 2]
💡 Note: Push 1,2,3; top shows 3 (most recent); pop removes 3; top now shows 2

Constraints

  • 1 ≤ x ≤ 9
  • At most 100 calls will be made to push, pop, top, and empty
  • All the calls to pop and top are guaranteed to be valid

Visualization

Tap to expand
Implementing Stack using Two QueuesSTACKLIFO321Top: 3SimulateQueue 1123Queue 2 (Helper)EmptyOperationspush(1) → O(1)push(2) → O(1)pop() → O(n)Queue Front = Stack Top (with proper element arrangement)Two approaches: Make push expensive OR make pop expensive
Understanding the Visualization
1
Input
Series of stack operations to perform
2
Process
Use two queues to maintain LIFO order
3
Output
Results of each operation in order
Key Takeaway
🎯 Key Insight: Use two queues to reverse the natural FIFO order and achieve LIFO stack behavior
Asked in
Bloomberg 15 Microsoft 12 Amazon 10 Apple 8
89.5K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen