Topics
A queue (FIFO) is implemented using two stacks (LIFO) with the following approach:
- Stack 1 (
st1) temporarily holds new elements when the front stack is non-empty - Stack 2 (
st2) holds elements in queue order. Allpopandpeekoperations are performed here
Key operations:
- Push:
- If
st2is empty, push directly tost2(this becomes the front) - If
st2is not empty, push tost1(waiting to be transferred later).
- If
- Pop:
- Remove the top of
st2(front of the queue). - If
st2becomes empty, transfer all elements fromst1tost2(reversing their order again to restore FIFO sequence).
- Remove the top of
Why It Works:
- Order Reversal: Transferring elements from
st1tost2reverses their order (LIFO → FIFO). - Lazy Transfer: Elements stay in
st1untilst2is empty, minimizing unnecessary operations.
Tip
Observe that
st2will only be empty when the queue itself is empty. So now, if a single element has to be pushed, we can push it tost2. This will make sure we can always dopeekin O(1). Further pushes should go tost1like usual.
void copy_from_st1_to_st2(stack<int> &st1, stack<int> &st2) {
while (!st1.empty()) {
st2.push(st1.top());
st1.pop();
}
}
void solve() {
int n;
cin >> n;
stack<int> st1, st2;
string cmd;
int val;
while (n--) {
cin >> cmd;
if (cmd == "push") {
cin >> val;
if (st2.empty())
st2.push(val);
else
st1.push(val);
} else if (cmd == "pop") {
if (!st2.empty()) {
cout << st2.top() << endl;
st2.pop();
}
if (st2.empty())
copy_from_st1_to_st2(st1, st2);
} else {
// cmd will be "front" or "peek"
if (!st2.empty())
cout << st2.top() << endl;
}
}
}Example
Commands:
push 1,push 2,push 3,peek,pop,pop,pop
- push 1
st2is empty →st2 = [1]- push 2
st2not empty →st1 = [2]- push 3
st2not empty →st1 = [2, 3]- peek
- return
st2.top()→1- pop (first)
- pop
1fromst2(nowst2 = [], i.e. empty)- Transfer
st1tost2:
- Pop
3fromst1→ push tost2(st2 = [3])- Pop
2fromst1→ push tost2(st2 = [3, 2])- pop (second)
- Pop
2fromst2(nowst2 = [3])- pop (third)
- Pop
3fromst2→st2is empty. No transfer needed asst1is emptyOutput:
1,1,2,3(correct FIFO order).
Amortized Time Complexity:
push: O(1)peek: O(1)pop: O(1) (amortized, as each element is moved at most twice)
Space Complexity: , where n is the number of elements.