23. Queue Reversal
β GFG solution to the Queue Reversal problem: reverse all elements in a queue using recursion, stack, or auxiliary data structures. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a queue q
containing integer elements, your task is to reverse the queue. The queue should be modified in-place such that the first element becomes the last, the second element becomes the second last, and so on.
A queue follows the FIFO (First In First Out) principle, but after reversal, the elements should appear in LIFO (Last In First Out) order when dequeued.
π Examples
Example 1
Input: q[] = [5, 10, 15, 20, 25]
Output: [25, 20, 15, 10, 5]
Explanation: After reversing the given elements of the queue, the resultant queue will be 25 20 15 10 5.
Example 2
Input: q[] = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: After reversing the given elements of the queue, the resultant queue will be 5 4 3 2 1.
Example 3
Input: q[] = [42]
Output: [42]
Explanation: A single element queue remains unchanged after reversal.
π Constraints
$1 \le \text{q.size()} \le 10^3$
$0 \le \text{q}[i] \le 10^5$
β
My Approach
The optimal approach uses Recursion to elegantly reverse the queue without requiring additional data structures for storage:
Recursive Approach
Base Case:
If the queue is empty, return immediately (nothing to reverse).
Recursive Step:
Remove the front element and store it temporarily.
Recursively reverse the remaining queue.
Add the stored element back to the queue (it will now be at the rear).
Stack Behavior:
The recursion call stack naturally provides LIFO behavior.
Elements are removed in FIFO order but added back in LIFO order.
In-Place Modification:
The original queue is modified without creating additional queues.
Uses only the implicit call stack for temporary storage.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the number of elements in the queue. Each element is processed exactly once during the recursive calls.
Expected Auxiliary Space Complexity: O(n), due to the recursion call stack. In the worst case, we have n recursive calls on the call stack simultaneously.
π§βπ» Code (C++)
class Solution {
public:
void reverseQueue(queue<int>& q) {
if (q.empty()) return;
int x = q.front();
q.pop();
reverseQueue(q);
q.push(x);
}
};
β Code (Java)
class Solution {
public void reverseQueue(Queue<Integer> q) {
if (q.isEmpty()) return;
int x = q.poll();
reverseQueue(q);
q.offer(x);
}
}
π Code (Python)
class Solution:
def reverseQueue(self, q):
s = []
while q:
s.append(q.popleft())
while s:
q.append(s.pop())
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated