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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem