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.
Only a stack can be used as an auxiliary space.
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
Following are the steps to solve the problem:
1.Push the first half elements of 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.
11 16 12 17 13 18 14 19 15 20
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 contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Interleave the first half of the queue with second half
- Priority queue of pairs in C++ with ordering by first and second element
- Stack and Queue in Python using queue Module
- Check if a queue can be sorted into another queue using a stack
- Reversing a Queue using another Queue
- Difference between Circular Queue and Priority Queue
- Maximum of XOR of first and second maximum of all subarrays
- Queue based approach for first non-repeating character in a stream
- Reversing the first K elements of a Queue
- FIFO (First-In-First-Out) approach in Programming
- Maximum sum of smallest and second smallest in an array
- Count subarrays where second highest lie before highest
- LRU Approximation (Second Chance Algorithm)
- Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Queue using Stacks
- Applications of Queue Data Structure
- Find the largest multiple of 3 | Set 1 (Using Queue)
- Queue Interface In Java
- Implement a stack using single queue