12. Reverse First K elements of Queue
The problem can be found at the following link: Question Link
My Approach
Initialize an empty stack temp and an empty queue ans.
Loop through the first 'k' elements of the input queue 'q'.
Push each element onto the stack 'temp'.
Remove each element from the front of the queue using q.pop().
Pop elements from the stack and enqueue them into the 'ans' queue, effectively reversing the order of the first 'k' elements.
Enqueue the remaining elements from the original queue 'q' into the 'ans' queue, maintaining their original order.
Return the modified 'ans' queue.
Time and Auxiliary Space Complexity
Time Complexity:
O(N)
, where N is the total number of elements in the queueAuxiliary Space Complexity:
O(N)
, where N is the total number of elements in the queue
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated