Solution Review: Reverse k Elements in a Queue

Let's discuss in detail the solution to the problem posed in the previous lesson.


We can solve this problem using a stack. We remove the first k elements from the queue and push them into the stack one by one. Then we pop the elements from the stack one by one and add them into the queue. The k elements are reversed, but they are added to the end of the queue. Therefore, we need to bring those elements to the start of the queue by removing the elements at the front and adding them to the back of the queue.

Let’s look at the illustration for a better understanding.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.