1. Brute Force — Array Conversion & Reverse
Intuition
Extract all items to an array, reverse the array, and push back to queue.
Algorithm
- Step 1: Dequeue all elements into a list.
- Step 2: Reverse the list using two pointers.
- Step 3: Enqueue all list elements back into the queue.
#include <iostream>#include <queue>#include <vector>#include <algorithm> using namespace std; class Solution {public: queue<int> rev(queue<int> q) { vector<int> temp; while (!q.empty()) { temp.push_back(q.front()); q.pop(); } reverse(temp.begin(), temp.end()); for (int x : temp) { q.push(x); } return q; }}; int main() { Solution sol; queue<int> q; q.push(4); q.push(3); q.push(1); q.push(10); q.push(2); q.push(6); queue<int> res = sol.rev(q); while (!res.empty()) { cout << res.front() << " "; res.pop(); } cout << endl; // 6 2 10 1 3 4 return 0;}Time & Space Complexity
- Time complexity:
O(N)— Dumping into array and reversing takes 2N operations. - Space complexity:
O(N)— Allocates auxiliary array of size N.
Why Brute Force Doesn't Scale:
Recursion on N = 105 causes segmentation fault / stack overflow.
Explicit iterative stack handles N = 106 elements in 8ms safely on heap memory.