![]() |
VOOZH | about |
Given an integer k and a queueq of integers, 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 the queue.
Example:
Input: q = 1 2 3 4 5, k = 3
Output: 3 2 1 4 5
Explanation: After reversing the first 3 elements from the given queue the resultant queue will be 3 2 1 4 5.Input: q = 4 3 2 1, k= 4
Output: 1 2 3 4
Explanation: After reversing the first 4 elements from the given queue the resultant queue will be 1 2 3 4.
Table of Content
The idea is to remove and store the first k elements in recursive call stack and insert them in the queue in the reverse order then we can simply remove and add remaining items of the queue.
Algorithm:
3 2 1 4 5
The idea is to use an auxiliary stack. Remove(dequeue) the first k elements from the queue and push them in a stack after this pop the elements from the stack and add(enqueue) them to the queue , after that simply remove(dequeue) the remaining n-k elements from the queue and add(enqueue) them back to the queue.
Algorithm:
3 2 1 4 5
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 k elements from the queue is emptied into the stack and then added back to the queue from the stack after that first 'n-k' elements are emptied and enqueued back to the queue.
Auxiliary Space: O(k) due to the stack used to store the first k elements.