12. Reverse First K elements of Queue
Last updated
Last updated
The problem can be found at the following link: Question Link
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 Complexity: O(N)
, where N is the total number of elements in the queue
Auxiliary Space Complexity: O(N)
, where N is the total number of elements in the queue
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.