GFG App
Open App
Browser
Continue

# Interleave the first half of the queue with second half

Given a queue of integers of even length, rearrange the elements by interleaving the first half of the queue with the second half of the queue.

Examples:

```Input :  1 2 3 4
Output : 1 3 2 4

Input : 11 12 13 14 15 16 17 18 19 20
Output : 11 16 12 17 13 18 14 19 15 20```

### Using Stack

Following are the steps to solve the problem:

1. Push the first half elements of the queue to stack.
2. Enqueue back the stack elements.
3. Dequeue the first half elements of the queue and enqueue them back.
4. Again push the first half elements into the stack.
5. Interleave the elements of queue and stack.

Implementation:

## C++

 `// C++ program to interleave the first half of the queue` `// with the second half` `#include ` `using` `namespace` `std;`   `// Function to interleave the queue` `void` `interLeaveQueue(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` `    ``// queue:16 17 18 19 20, stack: 15(T) 14 13 12 11` `    ``for` `(``int` `i = 0; i < halfSize; i++) {` `        ``s.push(q.front());` `        ``q.pop();` `    ``}`   `    ``// enqueue back the stack elements` `    ``// queue: 16 17 18 19 20 15 14 13 12 11` `    ``while` `(!s.empty()) {` `        ``q.push(s.top());` `        ``s.pop();` `    ``}`   `    ``// dequeue the first half elements of queue` `    ``// and enqueue them back` `    ``// queue: 15 14 13 12 11 16 17 18 19 20` `    ``for` `(``int` `i = 0; i < halfSize; i++) {` `        ``q.push(q.front());` `        ``q.pop();` `    ``}`   `    ``// Again push the first half elements into the stack` `    ``// queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15` `    ``for` `(``int` `i = 0; i < halfSize; i++) {` `        ``s.push(q.front());` `        ``q.pop();` `    ``}`   `    ``// interleave the elements of queue and stack` `    ``// queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `(!s.empty()) {` `        ``q.push(s.top());` `        ``s.pop();` `        ``q.push(q.front());` `        ``q.pop();` `    ``}` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``queue<``int``> q;` `    ``q.push(11);` `    ``q.push(12);` `    ``q.push(13);` `    ``q.push(14);` `    ``q.push(15);` `    ``q.push(16);` `    ``q.push(17);` `    ``q.push(18);` `    ``q.push(19);` `    ``q.push(20);` `    ``interLeaveQueue(q);` `    ``int` `length = q.size();` `    ``for` `(``int` `i = 0; i < length; i++) {` `        ``cout << q.front() << ``" "``;` `        ``q.pop();` `    ``}` `    ``return` `0;` `}`

## Java

 `// Java program to interleave` `// the first half of the queue` `// with the second half` `import` `java.util.*;`   `class` `GFG {`   `    ``// Function to interleave the queue` `    ``static` `void` `interLeaveQueue(Queue 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 int type` `        ``Stack s = ``new` `Stack<>();` `        ``int` `halfSize = q.size() / ``2``;`   `        ``// Push first half elements into the stack` `        ``// queue:16 17 18 19 20, stack: 15(T) 14 13 12 11` `        ``for` `(``int` `i = ``0``; i < halfSize; i++) {` `            ``s.push(q.peek());` `            ``q.poll();` `        ``}`   `        ``// enqueue back the stack elements` `        ``// queue: 16 17 18 19 20 15 14 13 12 11` `        ``while` `(!s.empty()) {` `            ``q.add(s.peek());` `            ``s.pop();` `        ``}`   `        ``// dequeue the first half elements of queue` `        ``// and enqueue them back` `        ``// queue: 15 14 13 12 11 16 17 18 19 20` `        ``for` `(``int` `i = ``0``; i < halfSize; i++) {` `            ``q.add(q.peek());` `            ``q.poll();` `        ``}`   `        ``// Again push the first half elements into the stack` `        ``// queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15` `        ``for` `(``int` `i = ``0``; i < halfSize; i++) {` `            ``s.push(q.peek());` `            ``q.poll();` `        ``}`   `        ``// interleave the elements of queue and stack` `        ``// queue: 11 16 12 17 13 18 14 19 15 20` `        ``while` `(!s.empty()) {` `            ``q.add(s.peek());` `            ``s.pop();` `            ``q.add(q.peek());` `            ``q.poll();` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``Queue q = ``new` `java.util.LinkedList<>();` `        ``q.add(``11``);` `        ``q.add(``12``);` `        ``q.add(``13``);` `        ``q.add(``14``);` `        ``q.add(``15``);` `        ``q.add(``16``);` `        ``q.add(``17``);` `        ``q.add(``18``);` `        ``q.add(``19``);` `        ``q.add(``20``);` `        ``interLeaveQueue(q);` `        ``int` `length = q.size();` `        ``for` `(``int` `i = ``0``; i < length; i++) {` `            ``System.out.print(q.peek() + ``" "``);` `            ``q.poll();` `        ``}` `    ``}` `}`   `// This code contributed by Rajput-Ji`

## Python3

 `# Python3 program to interleave the first` `# half of the queue with the second half` `from` `queue ``import` `Queue`   `# Function to interleave the queue`     `def` `interLeaveQueue(q):`   `    ``# To check the even number of elements` `    ``if` `(q.qsize() ``%` `2` `!``=` `0``):` `        ``print``(``"Input even number of integers."``)`   `    ``# Initialize an empty stack of int type` `    ``s ``=` `[]` `    ``halfSize ``=` `int``(q.qsize() ``/` `2``)`   `    ``# put first half elements into` `    ``# the stack queue:16 17 18 19 20,` `    ``# stack: 15(T) 14 13 12 11` `    ``for` `i ``in` `range``(halfSize):` `        ``s.append(q.queue[``0``])` `        ``q.get()`   `    ``# enqueue back the stack elements` `    ``# queue: 16 17 18 19 20 15 14 13 12 11` `    ``while` `len``(s) !``=` `0``:` `        ``q.put(s[``-``1``])` `        ``s.pop()`   `    ``# dequeue the first half elements of` `    ``# queue and enqueue them back` `    ``# queue: 15 14 13 12 11 16 17 18 19 20` `    ``for` `i ``in` `range``(halfSize):` `        ``q.put(q.queue[``0``])` `        ``q.get()`   `    ``# Again put the first half elements into` `    ``# the stack queue: 16 17 18 19 20,` `    ``# stack: 11(T) 12 13 14 15` `    ``for` `i ``in` `range``(halfSize):` `        ``s.append(q.queue[``0``])` `        ``q.get()`   `    ``# interleave the elements of queue and stack` `    ``# queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `len``(s) !``=` `0``:` `        ``q.put(s[``-``1``])` `        ``s.pop()` `        ``q.put(q.queue[``0``])` `        ``q.get()`     `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    ``q ``=` `Queue()` `    ``q.put(``11``)` `    ``q.put(``12``)` `    ``q.put(``13``)` `    ``q.put(``14``)` `    ``q.put(``15``)` `    ``q.put(``16``)` `    ``q.put(``17``)` `    ``q.put(``18``)` `    ``q.put(``19``)` `    ``q.put(``20``)` `    ``interLeaveQueue(q)` `    ``length ``=` `q.qsize()` `    ``for` `i ``in` `range``(length):` `        ``print``(q.queue[``0``], end``=``" "``)` `        ``q.get()`   `# This code is contributed by PranchalK`

## C#

 `// C# program to interleave` `// the first half of the queue` `// with the second half` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `    ``// Function to interleave the queue` `    ``static` `void` `interLeaveQueue(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` `        ``// queue:16 17 18 19 20, stack: 15(T) 14 13 12 11` `        ``for` `(``int` `i = 0; i < halfSize; i++) {` `            ``s.Push(q.Peek());` `            ``q.Dequeue();` `        ``}`   `        ``// enqueue back the stack elements` `        ``// queue: 16 17 18 19 20 15 14 13 12 11` `        ``while` `(s.Count != 0) {` `            ``q.Enqueue(s.Peek());` `            ``s.Pop();` `        ``}`   `        ``// dequeue the first half elements of queue` `        ``// and enqueue them back` `        ``// queue: 15 14 13 12 11 16 17 18 19 20` `        ``for` `(``int` `i = 0; i < halfSize; i++) {` `            ``q.Enqueue(q.Peek());` `            ``q.Dequeue();` `        ``}`   `        ``// Again push the first half elements into the stack` `        ``// queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15` `        ``for` `(``int` `i = 0; i < halfSize; i++) {` `            ``s.Push(q.Peek());` `            ``q.Dequeue();` `        ``}`   `        ``// interleave the elements of queue and stack` `        ``// queue: 11 16 12 17 13 18 14 19 15 20` `        ``while` `(s.Count != 0) {` `            ``q.Enqueue(s.Peek());` `            ``s.Pop();` `            ``q.Enqueue(q.Peek());` `            ``q.Dequeue();` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main(String[] args)` `    ``{` `        ``Queue<``int``> q = ``new` `Queue<``int``>();` `        ``q.Enqueue(11);` `        ``q.Enqueue(12);` `        ``q.Enqueue(13);` `        ``q.Enqueue(14);` `        ``q.Enqueue(15);` `        ``q.Enqueue(16);` `        ``q.Enqueue(17);` `        ``q.Enqueue(18);` `        ``q.Enqueue(19);` `        ``q.Enqueue(20);` `        ``interLeaveQueue(q);` `        ``int` `length = q.Count;` `        ``for` `(``int` `i = 0; i < length; i++) {` `            ``Console.Write(q.Peek() + ``" "``);` `            ``q.Dequeue();` `        ``}` `    ``}` `}`   `// This code is contributed by Princi Singh`

## Javascript

 ``

Output

`11 16 12 17 13 18 14 19 15 20 `

Time complexity: O(n). Auxiliary Space: O(n).

### Using Queue

We can also solve the given problem by using a queue instead of a stack. 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.

Move the first half to the temporary queue

Interleaving the two halves

## C++

 `// C++ program to interleave the first half of the queue` `// with the second half using queue` `#include ` `using` `namespace` `std;`   `// Function to interleave the queue` `void` `interLeaveQueue(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 queue of int type` `    ``queue<``int``> temp;` `    ``int` `halfSize = q.size() / 2;`   `    ``// Push first half elements into the stack` `    ``// queue:16 17 18 19 20, queue: 11 12 13 14 15` `    ``for` `(``int` `i = 0; i < halfSize; i++) {` `        ``temp.push(q.front());` `        ``q.pop();` `    ``}`   `    ``// enqueue back the queue elements alternatively` `    ``// queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `(!temp.empty()) {` `        ``q.push(temp.front());` `        ``q.push(q.front());` `        ``q.pop();` `        ``temp.pop();` `    ``}` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``queue<``int``> q;` `    ``q.push(11);` `    ``q.push(12);` `    ``q.push(13);` `    ``q.push(14);` `    ``q.push(15);` `    ``q.push(16);` `    ``q.push(17);` `    ``q.push(18);` `    ``q.push(19);` `    ``q.push(20);` `    ``interLeaveQueue(q);` `    ``int` `length = q.size();` `    ``for` `(``int` `i = 0; i < length; i++) {` `        ``cout << q.front() << ``" "``;` `        ``q.pop();` `    ``}` `    ``return` `0;` `}`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG {` `    ``static` `void` `interLeaveQueue(Queue q)` `    ``{` `      `  `    ``// To check the even number of elements` `    ``if` `(q.size() % ``2` `!= ``0``)` `        ``System.out.println(``"Input even number of integers."``);`   `    ``// Initialize an empty queue of int type` `    ``Queue temp=``new` `LinkedList<>();` `    ``int` `halfSize = q.size() / ``2``;`   `    ``// Push first half elements into the stack` `    ``// queue:16 17 18 19 20, queue: 11 12 13 14 15` `    ``for` `(``int` `i = ``0``; i < halfSize; i++) {` `        ``temp.add(q.peek());` `        ``q.remove();` `    ``}` `      `  `    ``// enqueue back the queue elements alternatively` `    ``// queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `(!temp.isEmpty()) {` `        ``q.add(temp.peek());` `        ``q.add(q.peek());` `        ``q.remove();` `        ``temp.remove();` `    ``}` `      `  `    ``}` `      `  `      `  `    ``public` `static` `void` `main (String[] args) {` `    ``Queue q=``new` `LinkedList<>();` `    ``q.add(``11``);` `    ``q.add(``12``);` `    ``q.add(``13``);` `    ``q.add(``14``);` `    ``q.add(``15``);` `    ``q.add(``16``);` `    ``q.add(``17``);` `    ``q.add(``18``);` `    ``q.add(``19``);` `    ``q.add(``20``);` `    ``interLeaveQueue(q);` `    ``int` `length = q.size();` `    ``for` `(``int` `i = ``0``; i < length; i++)` `    ``{` `        ``System.out.print(q.peek() + ``" "``);` `        ``q.remove();` `    ``}` `    ``}` `}`   `// This code is contributed by sourabhdalal0001`

## Python3

 `# Python3 program to interleave the first half of the queue` `# with the second half using queue`   `# Function to interleave the queue` `def` `interLeaveQueue(q):` `  `  `  ``# To check the even number of elements` `  ``if` `(``len``(q) ``%` `2` `!``=` `0``):` `    ``print``(``"Input even number of integers."``)`   `  ``# Initialize an empty queue of int type` `  ``temp ``=` `[]` `  ``halfSize ``=` `int``(``len``(q) ``/` `2``)`   `  ``# Push first half elements into the stack` `  ``# queue:16 17 18 19 20, queue: 11 12 13 14 15` `  ``for` `i ``in` `range``(``0``, halfSize):` `    ``temp.append(q[``0``])` `    ``q.pop(``0``)`   `  ``# enqueue back the queue elements alternatively` `  ``# queue: 11 16 12 17 13 18 14 19 15 20` `  ``while` `(``len``(temp)>``0``):` `    ``q.append(temp[``0``])` `    ``q.append(q[``0``])` `    ``q.pop(``0``)` `    ``temp.pop(``0``)`   `# Driver program to test above function` `q ``=` `[]` `q.append(``11``)` `q.append(``12``)` `q.append(``13``)` `q.append(``14``)` `q.append(``15``)` `q.append(``16``)` `q.append(``17``)` `q.append(``18``)` `q.append(``19``)` `q.append(``20``)` `interLeaveQueue(q)` `length ``=` `len``(q)` `print``(q)`   `# This code is contributed by akashish__`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {`   `  ``// Function to interleave the queue` `  ``public` `static` `void` `interLeaveQueue(``ref` `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 queue of int type` `    ``Queue<``int``> temp = ``new` `Queue<``int``>();` `    ``int` `halfSize = q.Count / 2;`   `    ``// Push first half elements into the stack` `    ``// queue:16 17 18 19 20, queue: 11 12 13 14 15` `    ``for` `(``int` `i = 0; i < halfSize; i++) {` `      ``temp.Enqueue(q.Peek());` `      ``q.Dequeue();` `    ``}`   `    ``// enqueue back the queue elements alternatively` `    ``// queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `(temp.Count > 0) {` `      ``q.Enqueue(temp.Peek());` `      ``q.Enqueue(q.Peek());` `      ``q.Dequeue();` `      ``temp.Dequeue();` `    ``}` `  ``}`   `  ``// Driver program to test above function` `  ``static` `public` `void` `Main()` `  ``{` `    ``Queue<``int``> q = ``new` `Queue<``int``>();` `    ``q.Enqueue(11);` `    ``q.Enqueue(12);` `    ``q.Enqueue(13);` `    ``q.Enqueue(14);` `    ``q.Enqueue(15);` `    ``q.Enqueue(16);` `    ``q.Enqueue(17);` `    ``q.Enqueue(18);` `    ``q.Enqueue(19);` `    ``q.Enqueue(20);` `    ``interLeaveQueue(``ref` `q);` `    ``int` `length = q.Count;` `    ``for` `(``int` `i = 0; i < length; i++) {` `      ``Console.Write(q.Peek());` `      ``Console.Write(``" "``);` `      ``q.Dequeue();` `    ``}` `  ``}` `}`

## Javascript

 `// JS program to interleave the first half of the queue` `// with the second half using queue`   `// Function to interleave the queue` `function` `interLeaveQueue(q) ` `{`   `    ``// To check the even number of elements` `    ``if` `(q.length % 2 != 0)` `        ``console.log(``"Input even number of integers."``);`   `    ``// Initialize an empty queue of int type` `    ``let temp = [];` `    ``let halfSize = q.length / 2;`   `    ``// Push first half elements into the stack` `    ``// queue:16 17 18 19 20, queue: 11 12 13 14 15` `    ``for` `(let i = 0; i < halfSize; i++) {` `        ``temp.push(q[0]);` `        ``q.shift();` `    ``}`   `    ``// enqueue back the queue elements alternatively` `    ``// queue: 11 16 12 17 13 18 14 19 15 20` `    ``while` `(temp.length != 0) {` `        ``q.push(temp[0]);` `        ``q.push(q[0]);` `        ``q.shift();` `        ``temp.shift();` `    ``}` `}`   `// Driver program to test above function` `let q = [];` `q.push(11);` `q.push(12);` `q.push(13);` `q.push(14);` `q.push(15);` `q.push(16);` `q.push(17);` `q.push(18);` `q.push(19);` `q.push(20);` `interLeaveQueue(q);` `let length = q.length;` `for` `(let i = 0; i < length; i++) {` `    ``console.log(q[0]) << ``" "``;` `    ``q.shift();` `}`   `// This code is contributed by adityamaharshi21`

Output

`11 16 12 17 13 18 14 19 15 20 `

This approach is contributed by Rudra Tiwari.

Time complexity: O(n)
Auxiliary Space: O(n).

This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up