Stack Using Two Queues
A Stack can be implemented using two Queues by maintaining the newest element at the front of one queue. One approach makes Push O(n) and Pop O(1): insert the new element into the empty queue, move all existing elements behind it, and then swap the queues.
Push complexity: O(n).
Pop complexity: O(1).
Peek complexity: O(1).
Auxiliary space: O(n).
The alternative design can make Push O(1) and Pop O(n), depending on the desired workload.
0-2 years experience
2-5 years experience
5-8 years experience