LeetCode 232 - Implement Queue using Stacks
LeetCode 232 - Implement Queue using Stacks
Table of Contents
Problem Statement
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).
Implement the MyQueue class:
void push(int x)Pushes element x to the back of the queue.int pop()Removes the element from the front of the queue and returns it.int peek()Returns the element at the front of the queue.boolean empty()Returnstrueif the queue is empty,falseotherwise.
Notes:
- You must use only standard operations of a stack, which means only
push to top,peek/pop from top,size, andis emptyoperations are valid. - Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stackβs standard operations.
Using Two Stacks
Explanation
push(int x):- Simply push the element onto the inputStack.
- Simply push the element onto the inputStack.
pop():- If outputStack is empty, transfer all elements from inputStack to outputStack. This reverses the order of elements, so the top of outputStack is the front of the queue.
- Pop the top element of outputStack.
peek():- Similar to pop(), but instead of removing the element, return the top of outputStack.
- Similar to pop(), but instead of removing the element, return the top of outputStack.
empty():- The queue is empty only if both stacks are empty.
- The queue is empty only if both stacks are empty.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class MyQueue {
private:
stack<int> inputStack;
stack<int> outputStack;
public:
MyQueue() {
}
void push(int x) {
inputStack.push(x);
}
int pop() {
if (outputStack.empty()) {
while (!inputStack.empty()) {
outputStack.push(inputStack.top());
inputStack.pop();
}
}
int front = outputStack.top();
outputStack.pop();
return front;
}
int peek() {
if (outputStack.empty()) {
while (!inputStack.empty()) {
outputStack.push(inputStack.top());
inputStack.pop();
}
}
return outputStack.top();
}
bool empty() {
return inputStack.empty() && outputStack.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
Conclusion
- Time Complexity:
- Push (π(1)) β Always inserts elements into
inputStack. - Pop (Amortized π(1)) β Moves elements from
inputStacktooutputStackwhenoutputStackis empty, then pops. - Peek (Amortized π(1)) β Similar to
pop(), but only returns the front element without removing that element. - Empty (π(1)) β Checks if both stacks are empty.
- Push (π(1)) β Always inserts elements into
- Space Complexity: π(π) β Where
nis the number of elements in the queue (storage across the two stacks).