1. Brute Force — Two Queues with Pop Costly
Intuition
Push easily to the end of q1. When popping, move all elements except the last one to q2, leaving the top element isolated.
Algorithm
- Step 1: push(x) enqueues x directly to q1.
- Step 2: pop() moves size - 1 elements from q1 to q2.
- Step 3: Pop the remaining single element in q1.
- Step 4: Swap queue references q1 and q2.
#include <iostream>#include <queue> using namespace std; class MyStack {private: queue<int> q1, q2;public: MyStack() {} void push(int x) { q1.push(x); } int pop() { while (q1.size() > 1) { q2.push(q1.front()); q1.pop(); } int topVal = q1.front(); q1.pop(); swap(q1, q2); return topVal; } int top() { while (q1.size() > 1) { q2.push(q1.front()); q1.pop(); } int topVal = q1.front(); q2.push(topVal); q1.pop(); swap(q1, q2); return topVal; } bool empty() { return q1.empty(); }}; int main() { MyStack st; st.push(1); st.push(2); cout << "Top: " << st.top() << endl; // 2 cout << "Pop: " << st.pop() << endl; // 2 cout << "Empty: " << (st.empty() ? "true" : "false") << endl; // false return 0;}Time & Space Complexity
- Time complexity:
Push: O(1), Pop: O(N), Top: O(N)— Moving N-1 elements from q1 to q2 takes O(N) on every pop/top. - Space complexity:
O(N)— Allocates two queues storing N elements.
Why Brute Force Doesn't Scale:
Two-queue pop-costly takes O(N) on every read, slowing down read-heavy workloads.
Single queue push-costly provides O(1) reads with zero extra object allocation overhead.