VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reversing-first-k-elements-queue/

⇱ Reversing the first K of a Queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reversing the first K of a Queue

Last Updated : 11 Apr, 2026

Given an integer k and a queueq of integers, reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.

Only following standard operations are allowed on the queue. 

  • enqueue(x): Add an item x to rear of queue
  • dequeue(): Remove an item from the front of the queue
  • size(): Returns the number of elements in the queue.
  • front(): Finds front item.

Example:

Input: q = 1 2 3 4 5, k = 3
Output: 3 2 1 4 5
Explanation: After reversing the first 3 elements from the given queue the resultant queue will be 3 2 1 4 5.

Input: q = 4 3 2 1, k= 4
Output: 1 2 3 4
Explanation: After reversing the first 4 elements from the given queue the resultant queue will be 1 2 3 4.

[Approach - 1] - Using the Recursion Call Stack - O(n)Time O(n)Space

The idea is to remove and store the first k elements in recursive call stack and insert them in the queue in the reverse order then we can simply remove and add remaining items of the queue.

Algorithm:

  • Recursively remove the first k elements, then add them back during backtracking → this reverses their order.
  • Rotate the remaining (n − k) elements from front to back → to maintain their original order.

Output
3 2 1 4 5 

[Approach - 2] - Using a Stack - O(n + k)Time O(k)Space

The idea is to use an auxiliary stack. Remove(dequeue) the first k elements from the queue and push them in a stack after this pop the elements from the stack and add(enqueue) them to the queue , after that simply remove(dequeue) the remaining n-k elements from the queue and add(enqueue) them back to the queue.

Algorithm:

  • Create an empty stack.
  • One by one dequeue first K items from given queue and push the dequeued items to stack.
  • Enqueue the contents of stack at the back of the queue
  • Dequeue (size-k) elements from the front and enqueue them one by one to the same queue.

Output
3 2 1 4 5 

Time Complexity: O(n + k), Where 'n' is the total number of elements in the queue and 'k' is the number of elements to be reversed. This is because firstly the k elements from the queue is emptied into the stack and then added back to the queue from the stack after that first 'n-k' elements are emptied and enqueued back to the queue.
Auxiliary Space: O(k) due to the stack used to store the first k elements.

Comment
Article Tags:
Article Tags: