Reverse first K elements of Queue using Stack

To reverse the first K elements of a queue, we can use an auxiliary stack. We push the first k elements in the stack and pop() them out so and add them at the end of the queue. Popping the elements out of the queue reverses them.

We can do this in linear time O(N) with O(K) space.

To bring the remaining n-k elements to their correct positions, we simply need to remove them from the front and add them at the end of the queue. After this operation the first K elements of the queue will be reversed...

 •  0 comments  •  flag
Share on Twitter
Published on May 21, 2021 00:21
No comments have been added yet.