![]() |
VOOZH | about |
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.
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:
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.
25 20 15 10 5
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:
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.
25 20 15 10 5
Time Complexity: O(n)
Auxiliary Space: O(n), due to recursion stack