VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reversing-a-queue/

⇱ Reversing a Queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reversing a Queue

Last Updated : 16 Sep, 2025

Given a queue q[], reverse the queue so that the front element becomes the rear and the rear element becomes the front, while preserving the order of the remaining elements accordingly.

Examples:

Input: q[] = [5, 10, 15, 20, 25]
Output: [25, 20, 15, 10, 5]
Explanation: The original front 5 moves to the rear, and the rear 25 becomes the new front. All other elements follow the reversed order.

Input: q[] = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: The queue is reversed completely: 1 goes to the rear, and 5 moves to the front, with all intermediate elements rearranged accordingly.

[Approach 1] Using Stack - O(n) Time and O(n) Space

To reverse the queue, we can use a stack data structure that follows the LIFO (Last In, First Out) principle. By storing the elements in stack, we can ensure that when the elements are re-inserted into the queue, they will appear in reverse order.

Working:

  • Pop the elements from the queue and insert into the stack now topmost element of the stack is the last element of the queue.
  • Pop the elements of the stack to insert back into the queue the last element is the first one to be inserted into the queue.

In JavaScript, there’s no built-in queue, so we use arrays. Removing elements with q.shift() takes O(n) time due to re-indexing, which makes repeated operations lead to an overall O(n²) time complexity.


Output
25 20 15 10 5 

[Approach 2] Using Recursion

A queue follows FIFO order (first in, first out). To reverse it, we need the front element to move to the rear, and repeat this process for all elements.

Here’s how to use recursion:

  • Remove the front element of the queue.
  • Recursively reverse the remaining queue.
  • Insert the removed element at the rear.

Recursion uses the call stack to remember removed elements. When the recursive calls return, those elements are added back in reverse order.

In JavaScript, there’s no built-in queue, so we use arrays. Removing elements with q.shift() takes O(n) time due to re-indexing, which makes repeated operations lead to an overall O(n²) time complexity.


Output
25 20 15 10 5 

Time Complexity: O(n)
Auxiliary Space: O(n), due to recursion stack

Comment
Article Tags:
Article Tags: