1. Brute Force — Push Costly (O(N) Push)
Intuition
Maintain the FIFO queue order inside s1 at all times by shifting existing elements to helper stack s2 before pushing.
Algorithm
- Step 1: Move all elements from stack s1 to helper stack s2.
- Step 2: Push the new element x onto stack s1.
- Step 3: Move all elements back from s2 onto s1.
- Step 4: Pop and peek directly return s1.top().
#include <iostream>#include <stack> using namespace std; class MyQueue {private: stack<int> s1, s2;public: MyQueue() {} void push(int x) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } s1.push(x); while (!s2.empty()) { s1.push(s2.top()); s2.pop(); } } int pop() { int val = s1.top(); s1.pop(); return val; } int peek() { return s1.top(); } bool empty() { return s1.empty(); }}; int main() { MyQueue q; q.push(1); q.push(2); cout << "Peek: " << q.peek() << endl; // 1 cout << "Pop: " << q.pop() << endl; // 1 cout << "Empty: " << (q.empty() ? "true" : "false") << endl; // false return 0;}Time & Space Complexity
- Time complexity:
Push: O(N), Pop: O(1)— Moving N elements between stacks on every push requires 2N operations. - Space complexity:
O(N)— Stores N elements across two stacks.
Why Brute Force Doesn't Scale:
With 105 operations, an O(N) per pop approach requires 1010 operations (TLE).
Lazy transfer processes 105 operations in under 5ms because each item moves at most twice.