710024. Interleave the First Half of the Queue with Second Half

Medium

Interleave the First Half of the Queue with Second Half

Summary

Given a queue, interleave the elements in the first half and second half. The problem can be solved by using a stack to store the elements from the first half and then pop them one by one and enqueue them along with the remaining elements from the second half.

Detailed Explanation

The solution involves two main steps: (1) storing the elements from the first half of the queue in a stack, and (2) popping the elements from the stack and enqueueing them along with the remaining elements from the second half.

Here is the step-by-step breakdown:

  1. Initialize an empty stack.
  2. Iterate over the queue until you reach the middle element.
  3. For each iteration, push the current element to the stack.
  4. Once you have reached the middle element, iterate over the rest of the queue and enqueue each element.
  5. Now, iterate over the stack and dequeue each element from the stack and enqueue them along with the remaining elements from the second half.

Time complexity: O(n), where n is the number of elements in the queue. This is because we are iterating over the queue twice.

Space complexity: O(n/2), as we are using a stack to store the elements from the first half of the queue.

Optimized Solutions

Java

View on GeeksforGeeks
public static void interleaveQueue(Queue<Integer> queue) {
    int n = queue.size();
    Stack<Integer> stack = new Stack<>();
    
    for (int i = 0; i < n / 2; i++) {
        stack.push(queue.poll());
    }
    
    while (!stack.isEmpty()) {
        queue.add(stack.pop());
    }
    
    while (!queue.isEmpty()) {
        queue.add(queue.poll());
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.