Given an integer k and a queue of integers, we need to reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.
Only following standard operations are allowed on queue.
- enqueue(x) : Add an item x to rear of queue
- dequeue() : Remove an item from front of queue
- size() : Returns number of elements in queue.
- front() : Finds front item.
Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] k = 5 Output : Q = [50, 40, 30, 20, 10, 60, 70, 80, 90, 100] Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] k = 4 Output : Q = [40, 30, 20, 10, 50, 60, 70, 80, 90, 100]
The idea is to use an auxiliary stack.
- Create an empty stack.
- One by one dequeue items from given queue and push the dequeued items to stack.
- Enqueue the contents of stack at the back of the queue
- Dequeue (size-k) elements from the front and enque them one by one to the same queue.
50 40 30 20 10 60 70 80 90 100
- Time Complexity: O(n+k).
Where ‘n’ is the total number of elements in the queue and ‘k’ is the number of elements to be reversed. This is because firstly the whole queue is emptied into the stack and after that first ‘k’ elements are emptied and enqueued in the same way.
- Auxiliary Space :Use of stack to store values for the purpose of reversing-: O(n)
This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Reversing a Queue
- Reversing a queue using recursion
- Reversing a Queue using another Queue
- Check if Queue Elements are pairwise consecutive | Set-2
- Check if Queue Elements are pairwise consecutive
- Append the elements of queue in mirror-inverse order
- Check if a queue can be sorted into another queue using a stack
- Stack and Queue in Python using queue Module
- Count of Array elements greater than all elements on its left and next K elements on its right
- Queue using Stacks
- Queue in Python
- Priority Queue in Python
- Sort the Queue using Recursion
- Reverse a path in BST using queue
- Priority Queue | Set 1 (Introduction)
- Sharing a queue among three threads
- Queue Interface In Java
- Queue of Pairs in C++ STL with Examples
- Applications of Priority Queue
- Priority Queue of Vectors in C++ STL with Examples