A catalog of data structures and problems with approaches to solve them
Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place.
Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.
Sample input:
[1, 2, 3, 4, 5]
Sample output:
[1, 5, 2, 4, 3]
If the stack is [1, 2, 3, 4]
, it should become [1, 4, 2, 3]
.
Try working backwards from the end state.
The steps will look as follows:
import math
from queue import Queue
def interleave(stack):
stack = [1, 2, 3, 4, 5]
queue = Queue()
size = len(stack)
while stack:
queue.put(stack.pop())
for _ in range(size // 2):
queue.put(queue.get())
for _ in range(math.ceil(size / 2.0)):
stack.append(queue.get())
for _ in range(size // 2):
queue.put(stack.pop())
queue.put(queue.get())
if stack:
queue.put(stack.pop())
while not queue.empty():
stack.append(queue.get())
return queue.queue, stack
interleave([1, 2, 3, 4, 5])
(deque([]), [1, 5, 2, 4, 3])