Reverse a Queue using recursion
Pattern: Implementation
Remove the front, reverse the rest recursively, then add the old front at the back. The call stack holds the fronts, so they come back newest first.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Reverse a queue using recursion. Queue 1, 2, 3, 4, 5 (front first) becomes 5, 4, 3, 2, 1. The function returns
nothing; the tests print the queue from front to back.
The catalogue has no practice link for this one.
Think first
- What is the simplest queue to reverse?
- If the rest is reversed, where does the old front go?
- What plays the role of a stack here?
Hints
Brute force, and why it fails
Pour the queue into a stack and back: O(n) with an explicit stack.
The key insight
A queue reversed is the old front placed after the reversed rest, and recursion supplies the stack needed to do that.
Dry run
| held | 1 2 3 |
|---|
Queue 1, 2, 3 (front on the left). Remove 1, then 2, then 3 down the calls.
The plan
reverse(q):
if q is empty: return
x = q.remove_front()
reverse(q)
q.add_back(x)
Complexity
- Time
O(n)- Space
O(n) call stack
Each item is removed and added once.
Edge cases
- Empty or one item.
- Deep queues: the tests stay at 150.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public void reverseQueue(Queue<Integer> q) {
if (q.isEmpty()) return;
int front = q.poll(); // hold the front on the call stack
reverseQueue(q); // reverse the rest
q.add(front); // the old front goes to the back
}
}C++
class Solution {
public:
void reverseQueue(queue<int>& q) {
if (q.empty()) return;
int front = q.front(); // hold the front on the call stack
q.pop();
reverseQueue(q); // reverse the rest
q.push(front); // the old front goes to the back
}
};Python
from collections import deque
class Solution:
def reverseQueue(self, q: deque) -> None:
if not q:
return
front = q.popleft() # hold the front on the call stack
self.reverseQueue(q) # reverse the rest
q.append(front) # the old front goes to the backCommon mistakes
- Adding the front back before the recursive call, which just rotates the queue.
- Using a deque's
pop()in Python, which takes from the back.