Open In App

Interleave the first half of the queue with second half

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Queue of even size. Your task is to rearrange the queue by interleaving its first half with the second half.

Note: Interleaving means place the first element from the first half and then first element from the 2nd half and again 2nd element from the first half and then second element from the 2nd half and so on....

Examples:

Input: q = [2, 4, 3, 1]
Output: [2, 3, 4, 1]
Explanation: we place the first element of the first half 2 and after that place the first element of second half 3 and after that repeat the same process one more time so the resulting queue will be [2, 3, 4, 1]

Input: q = [3, 5]
Output: [3, 5]
Explanation: We place the first element of the first half 3 and first element of the second half 5 so the resulting queue is [3, 5]

Using Stack - O(n) time and O(n) space

The idea is to first the first half of the elements in a stack (in a way that the top item is the first item of queue) and second half in queue. And then interleave items of queue and stack into the queue.

How do we get the first half of elements in stack?
This is tricky, we first get the first half elements into stack, but this is not desired order. To get the desired (or reverse order), we again enqueue these items and then dequeue the first half. After this step, the remaining elements in queue are the original first half in reverse order. We push these items in stack and get the items in stack in the desired order.

Following are the steps to solve the problem. Let us understand with an example q = [1, 2, 3, 4, 5, 6]

  1. Push the first half elements of the queue to stack, q = [4, 5, 6], s = [3, 2, 1]
  2. Enqueue back the stack elements.  q = [4, 5, 6, 3, 2, 1], s = []
  3. Dequeue the first half elements of the queue and enqueue them back. q = [3, 2, 1, 4, 5, 6], s = []
  4. Again push the first half elements into the stack.  q = [4, 5, 6], s = [1, 2, 3]
  5. Interleave the elements of queue and stack. q = [1, 4, 2, 5, 3, 6]
C++
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

void rearrangeQueue(queue<int>& q)
{
    // To check the even number of elements
    if (q.size() % 2 != 0)
        cout << "Input even number of integers." << endl;

    // Initialize an empty stack of int type
    stack<int> s;
    int halfSize = q.size() / 2;

    // Push first half elements into the stack
    for (int i = 0; i < halfSize; i++) {
        s.push(q.front());
        q.pop();
    }

    // enqueue back the stack elements
    while (!s.empty()) {
        q.push(s.top());
        s.pop();
    }

    // dequeue the first half elements of
    // queue and enqueue them back
    for (int i = 0; i < halfSize; i++) {
        q.push(q.front());
        q.pop();
    }

    // Again push the first half elements into the stack
    for (int i = 0; i < halfSize; i++) {
        s.push(q.front());
        q.pop();
    }

    // interleave the elements of queue and stack
    while (!s.empty()) {
        q.push(s.top());
        s.pop();
        q.push(q.front());
        q.pop();
    }
}

int main()
{
    queue<int> q;
    q.push(2);
    q.push(4);
    q.push(3);
    q.push(1);
    rearrangeQueue(q);
    int length = q.size();
    for (int i = 0; i < length; i++) {
        cout << q.front() << " ";
        q.pop();
    }
    return 0;
}
Java
import java.util.*;

public class GfG {
    public static void rearrangeQueue(Queue<Integer> q) {
        
        // To check the even number of elements
        if (q.size() % 2 != 0)
            System.out.println("Input even number of integers.");

        // Initialize an empty stack of Integer type
        Stack<Integer> s = new Stack<>();
        int halfSize = q.size() / 2;

        // Push first half elements into the stack
        for (int i = 0; i < halfSize; i++) {
            s.push(q.poll());
        }

        // enqueue back the stack elements
        while (!s.isEmpty()) {
            q.add(s.pop());
        }

        // dequeue the first half elements of queue and enqueue them back
        for (int i = 0; i < halfSize; i++) {
            q.add(q.poll());
        }

        // Again push the first half elements into the stack
        for (int i = 0; i < halfSize; i++) {
            s.push(q.poll());
        }

        // interleave the elements of queue and stack
        while (!s.isEmpty()) {
            q.add(s.pop());
            q.add(q.poll());
        }
    }

    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();
        q.add(2);
        q.add(4);
        q.add(3);
        q.add(1);
        rearrangeQueue(q);
        int length = q.size();
        for (int i = 0; i < length; i++) {
            System.out.print(q.poll() + " ");
        }
    }
}
Python
from collections import deque

def rearrangeQueue(q):
    # To check the even number of elements
    if len(q) % 2 != 0:
        print("Input even number of integers.")
        return

    # Initialize an empty stack
    stack = []
    halfSize = len(q) // 2

    # Push first half elements into the stack
    for _ in range(halfSize):
        stack.append(q.popleft())

    # enqueue back the stack elements
    while stack:
        q.append(stack.pop())

    # dequeue the first half elements of queue and enqueue them back
    for _ in range(halfSize):
        q.append(q.popleft())

    # Again push the first half elements into the stack
    for _ in range(halfSize):
        stack.append(q.popleft())

    # interleave the elements of queue and stack
    while stack:
        q.append(stack.pop())
        q.append(q.popleft())

def main():
    q = deque([2, 4, 3, 1]) 
    rearrangeQueue(q)
    print(" ".join(map(str, q)))

if __name__ == "__main__":
    main()
C#
using System;
using System.Collections.Generic;

class GfG {
    static void RearrangeQueue(Queue<int> q) {
        // To check the even number of elements
        if (q.Count % 2 != 0)
            Console.WriteLine("Input even number of integers.");

        // Initialize an empty stack of int type
        Stack<int> s = new Stack<int>();
        int halfSize = q.Count / 2;

        // Push first half elements into the stack
        for (int i = 0; i < halfSize; i++) {
            s.Push(q.Dequeue());
        }

        // Enqueue back the stack elements
        while (s.Count > 0) {
            q.Enqueue(s.Pop());
        }

        // Dequeue the first half elements of queue and enqueue them back
        for (int i = 0; i < halfSize; i++) {
            q.Enqueue(q.Dequeue());
        }

        // Again push the first half elements into the stack
        for (int i = 0; i < halfSize; i++) {
            s.Push(q.Dequeue());
        }

        // Interleave the elements of queue and stack
        while (s.Count > 0) {
            q.Enqueue(s.Pop());
            q.Enqueue(q.Dequeue());
        }
    }

    static void Main() {
        Queue<int> q = new Queue<int>();
        q.Enqueue(2);
        q.Enqueue(4);
        q.Enqueue(3);
        q.Enqueue(1);
        RearrangeQueue(q);
        int length = q.Count;
        for (int i = 0; i < length; i++) {
            Console.Write(q.Dequeue() + " ");
        }
    }
}
JavaScript
function rearrangeQueue(q) {
    if (q.length % 2 !== 0) {
        console.log("Input even number of integers.");
        return;
    }

    let s = [];
    let halfSize = q.length / 2;

    // Step 1: Push first half into the stack
    for (let i = 0; i < halfSize; i++) {
        s.push(q.shift());
    }

    // Step 2: Enqueue back the stack contents to the queue
    while (s.length > 0) {
        q.push(s.pop());
    }

    // Step 3: Move the first half of the queue (which was second half initially) to the back
    for (let i = 0; i < halfSize; i++) {
        q.push(q.shift());
    }

    // Step 4: Again push first half into the stack
    for (let i = 0; i < halfSize; i++) {
        s.push(q.shift());
    }

    // Step 5: Interleave elements of stack and queue
    while (s.length > 0) {
        q.push(s.pop());   
        q.push(q.shift()); 
    }
}

let q = [2, 4, 3, 1];
rearrangeQueue(q);

console.log(q.join(" "));

Output
2 3 4 1 

Using Queue - O(n) time and O(n) space

The idea is to move the first half to another queue and then push values from the temporary queue and original queue into the original queue. The original queue will get converted to the interleaved queue after the operations.

Steps to solve: 

  1. Make a temporary queue and push the first half of the original queue into the temp queue.
  2. Till the temp queue is empty
    1. Pop the front of the temp queue and push it to the original queue
    2. Pop the front of the original queue and push it to the original queue
  3. The original queue is converted to the interleaved queue.
C++
#include <iostream>
#include <queue>
using namespace std;

queue<int> rearrangeQueue(queue<int> q) {
    int n = q.size();  
    queue<int> first_half, second_half, result;

    for (int i = 0; i < n / 2; i++) {  
        first_half.push(q.front());
        q.pop();
    }

    while (!q.empty()) {
        second_half.push(q.front());
        q.pop();
    }

    while (!first_half.empty() && !second_half.empty()) {
        result.push(first_half.front());
        first_half.pop();
        result.push(second_half.front());
        second_half.pop();
    }

    return result;
}

int main() {
    queue<int> q;
    q.push(2);
    q.push(4);
    q.push(3);
    q.push(1);

    queue<int> result = rearrangeQueue(q);

    while (!result.empty()) {
        cout << result.front() << " ";
        result.pop();
    }

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

public class GfG {
    public static Queue<Integer> rearrangeQueue(Queue<Integer> q) {
        int n = q.size();  
        Queue<Integer> first_half = new LinkedList<>();
        Queue<Integer> second_half = new LinkedList<>();
        Queue<Integer> result = new LinkedList<>();

        for (int i = 0; i < n / 2; i++) {  
            first_half.add(q.poll());
        }

        while (!q.isEmpty()) {
            second_half.add(q.poll());
        }

        while (!first_half.isEmpty() && !second_half.isEmpty()) {
            result.add(first_half.poll());
            result.add(second_half.poll());
        }

        return result;
    }

    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();
        q.add(2);
        q.add(4);
        q.add(3);
        q.add(1);

        Queue<Integer> result = rearrangeQueue(q);

        while (!result.isEmpty()) {
            System.out.print(result.poll() + " ");
        }
    }
}
Python
from collections import deque

def rearrangeQueue(q):
    n = len(q)
    first_half = deque()
    second_half = deque()
    result = deque()

    for _ in range(n // 2):
        first_half.append(q.popleft())

    while q:
        second_half.append(q.popleft())

    while first_half and second_half:
        result.append(first_half.popleft())
        result.append(second_half.popleft())

    return result

if __name__ == '__main__':
    q = deque([2, 4, 3, 1])
    result = rearrangeQueue(q)

    while result:
        print(result.popleft(), end=' ')
C#
using System;
using System.Collections.Generic;

class GfG {
    public static Queue<int> RearrangeQueue(Queue<int> q) {
        int n = q.Count;
        Queue<int> first_half = new Queue<int>();
        Queue<int> second_half = new Queue<int>();
        Queue<int> result = new Queue<int>();

        for (int i = 0; i < n / 2; i++) {
            first_half.Enqueue(q.Dequeue());
        }

        while (q.Count > 0) {
            second_half.Enqueue(q.Dequeue());
        }

        while (first_half.Count > 0 && second_half.Count > 0) {
            result.Enqueue(first_half.Dequeue());
            result.Enqueue(second_half.Dequeue());
        }

        return result;
    }

    static void Main() {
        Queue<int> q = new Queue<int>();
        q.Enqueue(2);
        q.Enqueue(4);
        q.Enqueue(3);
        q.Enqueue(1);

        Queue<int> result = RearrangeQueue(q);

        while (result.Count > 0) {
            Console.Write(result.Dequeue() + " ");
        }
    }
}
JavaScript
function rearrangeQueue(q) {
    const n = q.length;
    const first_half = [];
    const second_half = [];
    const result = [];

    // Push first half elements into the first_half array
    for (let i = 0; i < Math.floor(n / 2); i++) {  
        first_half.push(q.shift());
    }

    // Push remaining elements into the second_half array
    while (q.length > 0) {
        second_half.push(q.shift());
    }

    // Interleave elements from first_half and second_half
    while (first_half.length > 0 && second_half.length > 0) {
        result.push(first_half.shift());
        result.push(second_half.shift());
    }

    return result;
}

const q = [];
q.push(2);
q.push(4);
q.push(3);
q.push(1);

const result = rearrangeQueue(q);

console.log(result.join(' '));

Output
2 3 4 1 

Getting Result in an Array - O(n) time and O(n) space

The approach splits the queue into two halves, then interleaves the elements from both halves into a result array. The first half's elements are placed at even indices and the second half's elements at odd indices of the array. This ensures an alternating order of elements from the first and second halves.

Steps to solve:

  1. First, you calculate the size n of the queue and initialize a vector ans of size n to store the result.
  2. You start by adding elements from the first half of the queue into even indices of the ans vector.
  3. Then, you add elements from the second half of the queue into odd indices of the ans vector.
  4. Finally, you return the ans vector which contains the interleaved elements.
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

vector<int> rearrangeQueue(queue<int>& q) {
    int n = q.size();
    vector<int> ans(n);  
    int i = 0, j = n / 2;

    // Interleave the elements into the ans vector
    while (!q.empty()) {
        if (i < n / 2) {
            ans[2 * i] = q.front();
            q.pop();
            i++;
        } else {
            ans[2 * i - n + 1] = q.front();
            q.pop();
            j--;
            i++;
        }
    }
    return ans;
}

int main() {
    queue<int> q;
    q.push(2);
    q.push(4);
    q.push(3);
    q.push(1);

    vector<int> result = rearrangeQueue(q);

    for (int num : result) {
        cout << num << " ";
    }
    return 0;
}
Java
import java.util.*;

public class GfG {
    public static int[] rearrangeQueue(Queue<Integer> q) {
        int n = q.size();
        int[] ans = new int[n];
        Arrays.fill(ans, -1);
        int i = 0, j = n / 2;

        // Interleave the elements into the ans array
        while (!q.isEmpty()) {
            if (i < n / 2) {
                ans[2 * i] = q.poll();
                i++;
            } else {
                ans[2 * i - n + 1] = q.poll();
                j--;
                i++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();
        q.add(2);
        q.add(4);
        q.add(3);
        q.add(1);

        int[] result = rearrangeQueue(q);

        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}
Python
from collections import deque

def rearrangeQueue(q):
    n = len(q)
    ans = [-1] * n
    i, j = 0, n // 2

    # Interleave the elements into the ans list
    while q:
        if i < n // 2:
            ans[2 * i] = q.popleft()
            i += 1
        else:
            ans[2 * i - n + 1] = q.popleft()
            j -= 1
            i += 1
    return ans

if __name__ == '__main__':
    q = deque([2, 4, 3, 1])
    result = rearrangeQueue(q)
    print(' '.join(map(str, result)))
C#
using System;
using System.Collections.Generic;

class GfG {
    static List<int> RearrangeQueue(Queue<int> q) {
        int n = q.Count;
        List<int> ans = new List<int>(new int[n]);
        int i = 0, j = n / 2;

        // Interleave the elements into the ans list
        while (q.Count > 0) {
            if (i < n / 2) {
                ans[2 * i] = q.Dequeue();
                i++;
            } else {
                ans[2 * i - n + 1] = q.Dequeue();
                j--;
                i++;
            }
        }
        return ans;
    }

    static void Main() {
        Queue<int> q = new Queue<int>();
        q.Enqueue(2);
        q.Enqueue(4);
        q.Enqueue(3);
        q.Enqueue(1);

        List<int> result = RearrangeQueue(q);

        foreach (int num in result) {
            Console.Write(num + " ");
        }
    }
}
JavaScript
function rearrangeQueue(q) {
    const n = q.length;
    const ans = new Array(n).fill(-1);
    let i = 0, j = Math.floor(n / 2);

    // Interleave the elements into the ans array
    while (q.length > 0) {
        if (i < Math.floor(n / 2)) {
            ans[2 * i] = q.shift();
            i++;
        } else {
            ans[2 * i - n + 1] = q.shift();
            j--;
            i++;
        }
    }
    return ans;
}

const q = [2, 4, 3, 1];
const result = rearrangeQueue(q);

result.forEach(num => {
    process.stdout.write(num + ' ');
});

Output
2 3 4 1 

Next Article
Article Tags :
Practice Tags :

Similar Reads