The Two Stacks
We designate `s1` as the Input Stack and `s2` as the Output Stack. Enqueuing is dead simple: just push to `s1`!
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Design a First-In-First-Out (FIFO) queue using only two standard Last-In-First-Out (LIFO) stacks. This is a classic FAANG interview question.
We designate `s1` as the Input Stack and `s2` as the Output Stack. Enqueuing is dead simple: just push to `s1`!
When someone calls dequeue, we need the OLDEST element. But `s1` holds the NEWEST element on top. So, we pop everything from `s1` and push it to `s2`. This completely reverses the order!
Transferring elements takes O(N) time. BUT, we only transfer when `s2` is totally empty. Most dequeue calls will just pop directly from `s2` in O(1) time. Over time, it averages out to O(1).