1. Isolate and Reverse
Pop the first K elements into a stack. This inherently reverses them. Then pop from the stack and enqueue them back. Now the reversed K elements are at the back of the queue.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an integer K and a queue, reverse the order of the first K elements, leaving the remaining elements in their original relative order.
Pop the first K elements into a stack. This inherently reverses them. Then pop from the stack and enqueue them back. Now the reversed K elements are at the back of the queue.
Wait, if they are at the back, the queue is out of order! `1, 2, 3, 4, 5` (k=3) became `4, 5, 3, 2, 1`. The unreversed elements `4, 5` are stuck at the front.
To fix this, simply dequeue the remaining `N - K` elements (`4, 5`) and immediately enqueue them back to the rear! This rotates the queue to `3, 2, 1, 4, 5`.