Interleave the first half of the queue with second half
Last Updated :
26 Apr, 2025
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]
- Push the first half elements of the queue to stack, q = [4, 5, 6], s = [3, 2, 1]
- Enqueue back the stack elements. q = [4, 5, 6, 3, 2, 1], s = []
- Dequeue the first half elements of the queue and enqueue them back. q = [3, 2, 1, 4, 5, 6], s = []
- Again push the first half elements into the stack. q = [4, 5, 6], s = [1, 2, 3]
- 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(" "));
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:
- Make a temporary queue and push the first half of the original queue into the temp queue.
- Till the temp queue is empty
- Pop the front of the temp queue and push it to the original queue
- Pop the front of the original queue and push it to the original queue
- 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(' '));
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:
- First, you calculate the size
n
of the queue and initialize a vector ans
of size n
to store the result. - You start by adding elements from the first half of the queue into even indices of the
ans
vector. - Then, you add elements from the second half of the queue into odd indices of the
ans
vector. - 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 + ' ');
});
Similar Reads
Find the arrangement of queue at given time
n people are standing in a queue to buy entry ticket for the carnival. People present there strongly believe in chivalry. Therefore, at time = t, if a man at position x, finds a woman standing behind him then he exchanges his position with her and therefore, at time = t+1, woman is standing at posit
6 min read
Most efficient way to implement Stack and Queue together
Introduction to Stack:A stack is a linear data structure in computer science that follows the Last-In-First-Out (LIFO) principle. It is a data structure in which the insertion and removal of elements can only be performed at one end, which is called the top of the stack.In a stack, elements are push
15+ min read
Interchange elements of Stack and Queue without changing order
Given a stack St of M elements and a queue Q of N elements. The task is to put every element of stack into the queue and every element of the queue into the stack without changing their order. Examples: Input: St = {4, 3, 2, 1}, Q = {8, 7, 6, 5}Output: St = {8, 7, 6, 5}, Q = {1, 2, 3, 4} Input: St =
11 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are process
8 min read
Find the final size of Congestion Window in TCP Tahoe
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Taho
8 min read
Check if it is possible to serve customer queue with different notes
Given cost of the ticket '25' and an integer array 'arr' which holds the values of the notes people in a queue are having (either '25', '50' or '100' Rs. Notes). The task is to find whether it possible to sell tickets to the people in order, starting from 0 Rs.Examples: Input: arr = {25, 25, 50, 50}
7 min read
Sorting a Queue without extra space
Given a queue with random elements, we need to sort it. We are not allowed to use extra space. The operations allowed on queue are : enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called push().dequeue() : Removes an item from front of queue. In C++ STL queue, this fun
9 min read
Implementation of Non-Preemptive Shortest Job First using Priority Queue
Read here for Shortest Job First Scheduling algorithm for same arrival times.Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next.In this article, we will implement the Shortest Job First Scheduling al
12 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push
9 min read
Program to find the final size of Congestion Window in TCP Reno
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Reno
7 min read