The Single Queue Approach
You actually only need ONE queue! When you push an element, enqueue it to the back. Then, immediately dequeue all the previous elements and enqueue them back into the same queue.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
How can you mimic the Last-In-First-Out (LIFO) behavior of a Stack using only First-In-First-Out (FIFO) Queues?
You actually only need ONE queue! When you push an element, enqueue it to the back. Then, immediately dequeue all the previous elements and enqueue them back into the same queue.
Because you must rotate `size - 1` elements every time you push, the push operation becomes O(N). This effectively reverses the queue every time a new element arrives, keeping the newest element at the front.
Because the push operation did all the heavy lifting to keep the newest element at the front, popping and peeking are extremely fast. Just `q.dequeue()` or `q.front()`.