1. Brute Force — Full Array Extraction & Slice Reversal
Intuition
Drain queue into an array, reverse the first K indices, and rebuild queue.
Algorithm
- Step 1: Drain queue into array
arr. - Step 2: Reverse
arr[0...K-1]using two pointers. - Step 3: Enqueue all elements of
arrback intoq.
#include <iostream>#include <queue>#include <vector>#include <algorithm> using namespace std; class Solution {public: queue<int> modifyQueue(queue<int> q, int k) { vector<int> arr; while (!q.empty()) { arr.push_back(q.front()); q.pop(); } reverse(arr.begin(), arr.begin() + k); for (int x : arr) { q.push(x); } return q; }}; int main() { Solution sol; queue<int> q; for (int i = 1; i <= 5; ++i) q.push(i); queue<int> res = sol.modifyQueue(q, 3); while (!res.empty()) { cout << res.front() << " "; res.pop(); } cout << endl; // 3 2 1 4 5 return 0;}Time & Space Complexity
- Time complexity:
O(N)— Dumping N elements to list and reversing prefix of size K takes O(N). - Space complexity:
O(N)— Allocates array of size N.
Why Brute Force Doesn't Scale:
Copying 105 elements between arrays causes unnecessary GC pressure.
Stack of size K with in-place rotation completes in under 3ms.