Reverse the first “K” elements of a queue
Pattern: Implementation
Move the first k items onto a stack, pour them back into the queue (now reversed, at the back), then move the other n - k items from the front to the back so they follow again.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a queue and k (at most its size), reverse the order of the first k items and keep the rest in order.
1, 2, 3, 4, 5 with k = 3 becomes 3, 2, 1, 4, 5. The function returns nothing; the tests print the queue from front
to back.
The catalogue has no practice link for this one.
Think first
- Which structure reverses a group of items?
- After the k reversed items are put back, where are they?
- How do you bring the other items behind them?
Hints
Brute force, and why it fails
Copy into an array, reverse the first k there and rebuild the queue: O(n), but it leaves the queue operations behind.
The key insight
A stack reverses the group, and rotating the queue by n - k moves the untouched part back behind it.
Dry run
| stack | 1 2 3 (3 on top) |
|---|
Queue 1, 2, 3, 4, 5 and k = 3. Move 1, 2, 3 to a stack.
The plan
repeat k times: stack.push(q.remove_front())
while stack: q.add_back(stack.pop())
repeat len(q) - k times: q.add_back(q.remove_front())
Complexity
- Time
O(n)- Space
O(k)
Each item moves a constant number of times; the stack holds k items.
Edge cases
- k = 1: unchanged.
- k = n: the whole queue is reversed and no rotation is needed.
- One item.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public void reverseFirstK(Queue<Integer> q, int k) {
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < k; i++) st.push(q.poll()); // the first k go onto a stack
while (!st.isEmpty()) q.add(st.pop()); // and come back reversed, at the back
for (int i = 0; i < q.size() - k; i++) q.add(q.poll()); // move the rest behind them
}
}C++
class Solution {
public:
void reverseFirstK(queue<int>& q, int k) {
stack<int> st;
for (int i = 0; i < k; i++) { st.push(q.front()); q.pop(); } // the first k go onto a stack
while (!st.empty()) { q.push(st.top()); st.pop(); } // and come back reversed, at the back
int rest = static_cast<int>(q.size()) - k;
for (int i = 0; i < rest; i++) { q.push(q.front()); q.pop(); } // move the rest behind them
}
};Python
from collections import deque
class Solution:
def reverseFirstK(self, q: deque, k: int) -> None:
st = []
for _ in range(k):
st.append(q.popleft()) # the first k go onto a stack
while st:
q.append(st.pop()) # and come back reversed, at the back
for _ in range(len(q) - k):
q.append(q.popleft()) # move the rest behind themCommon mistakes
- Forgetting the final rotation, which leaves the reversed part at the back.
- Rotating
ntimes instead ofn - k.