Interleave the first half of the queue with second half
Pattern: Implementation
Take the first half out into a second queue. Then, until it is empty, add one item from it to the back of the original queue, followed by one item moved from the original's front. The halves end up alternating.
The problem
Given a queue of even length, rearrange it so the first half and the second half alternate: first item of the first
half, first of the second half, second of the first half, and so on. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 becomes
11, 16, 12, 17, 13, 18, 14, 19, 15, 20. The function returns nothing; the tests print the queue from front to back.
Think first
- Where can the first half wait?
- After it is removed, what is at the front of the original queue?
- What order of adds builds the answer at the back?
Hints
Brute force, and why it fails
Copy into an array and build the answer there: O(n) time and space, outside the queue rules.
The key insight
After removing the first half, the original queue holds the second half at its front, so each step can take one item from each half and append them in turn.
Dry run
| first | 1 2 |
|---|
Queue 1, 2, 3, 4. Move the first half 1, 2 to a second queue.
The plan
half = len(q) / 2
first = queue of the first `half` items removed from q
while first is not empty:
q.add_back(first.remove_front())
q.add_back(q.remove_front())
Complexity
- Time
O(n)- Space
O(n)
Each item moves a constant number of times; the second queue holds half the items.
Edge cases
- Two items: unchanged.
- Empty queue.
- The linked page solves it with a stack instead; a queue keeps the order without extra reversals.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public void interleave(Queue<Integer> q) {
int half = q.size() / 2;
Queue<Integer> first = new ArrayDeque<>();
for (int i = 0; i < half; i++) first.add(q.poll()); // take the first half out
while (!first.isEmpty()) {
q.add(first.poll()); // one from the first half
q.add(q.poll()); // then one from the second half
}
}
}C++
class Solution {
public:
void interleave(queue<int>& q) {
int half = static_cast<int>(q.size()) / 2;
queue<int> first;
for (int i = 0; i < half; i++) { first.push(q.front()); q.pop(); } // take the first half out
while (!first.empty()) {
q.push(first.front()); first.pop(); // one from the first half
q.push(q.front()); q.pop(); // then one from the second half
}
}
};Python
from collections import deque
class Solution:
def interleave(self, q: deque) -> None:
half = len(q) // 2
first = deque(q.popleft() for _ in range(half)) # take the first half out
while first:
q.append(first.popleft()) # one from the first half
q.append(q.popleft()) # then one from the second halfCommon mistakes
- Using a stack for the first half without reversing it again, which interleaves it backwards.
- Reading
q.size()inside the loop while it changes.