How to solve Reversing First K Elements of a Queue

GFG · Medium · Queue · Pattern: Queue + Stack

Why the obvious approach is slow

A queue only lets you take from the front and add to the back. So you cannot simply reverse part of it in place.

The key idea

A stack reverses order, so use one. Move the first k elements from the queue into the stack. Pop them all back into the queue, which adds them to the back in reversed order. Finally, rotate the other n minus k elements from the front to the back, so the reversed part is at the front again.

Remember

A stack reverses, a queue rotates. Reverse the first k, then rotate the rest to the back.

Run the animation above on your own input, or watch the 1:17 video explanation of Reversing First K Elements of a Queue with a dry run and Java code.

More Queue problems