
Problem
Solution
Submissions
Queue Using Two Stacks
Certification: Intermediate Level
Accuracy: 0%
Submissions: 1
Points: 10
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Example 1
- Input: ["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []] - Output: [null, null, null, 1, 1, false]
- Explanation:
- MyQueue myQueue = new MyQueue();
- myQueue.push(1); // queue is: [1]
- myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
- myQueue.peek(); // return 1
- myQueue.pop(); // return 1, queue is [2]
- myQueue.empty(); // return false
Example 2
- Input: ["MyQueue", "push", "push", "push", "pop", "push", "pop", "pop", "pop", "empty"]
[[], [1], [2], [3], [], [4], [], [], [], []] - Output: [null, null, null, null, 1, null, 2, 3, 4, true]
- Explanation:
- MyQueue myQueue = new MyQueue();
- myQueue.push(1); // queue is: [1]
- myQueue.push(2); // queue is: [1, 2]
- myQueue.push(3); // queue is: [1, 2, 3]
- myQueue.pop(); // return 1, queue is [2, 3]
- myQueue.push(4); // queue is: [2, 3, 4]
- myQueue.pop(); // return 2, queue is [3, 4]
- myQueue.pop(); // return 3, queue is [4]
- myQueue.pop(); // return 4, queue is []
- myQueue.empty(); // return true, queue is empty
Constraints
- 1 ≤ x ≤ 9
- At most 100 calls will be made to push, pop, peek, and empty
- All the calls to pop and peek are valid
- Time Complexity: O(1) amortized for all operations
- Space Complexity: O(n) where n is the number of elements in the queue
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use one stack for pushing elements and another stack for popping elements
- When performing a pop or peek operation, if the "pop stack" is empty, transfer all elements from the "push stack" to the "pop stack"
- This way, the elements are reversed and follow the FIFO order
- Elements are only moved from the push stack to the pop stack when necessary, making the amortized time complexity O(1) for all operations
- Remember that a stack is Last-In-First-Out (LIFO), but a queue is First-In-First-Out (FIFO)