0
votes

How can one reverse a Queue in O(1) space complexity?

The answer here: Can I reverse a queue without using stack? says that it is possible with a stack. But I don’t understand how this process is O(1) space complexity:

Step 1: Enqueue then Dequeue every element of a Queue into a Stack

Step 2: Enqueue the Front value of the Stack into the Queue then Pop off every element of the Stack

Wouldn’t the Stack use O(n) space complexity for every element in the Queue?

1

1 Answers

1
votes

When you add an element to stack, you remove it from queue. Sum of queue size and stack size does not change, so total amount of used memory remains the same. That's why it takes O(1) space.