Problem Statement
Implement Stack using Queues
A stack is like a pile of plates. You only ever touch the top, you add a plate to the top and you take a plate from the top, so the last plate you put on is the first one you take off. That rule is called LIFO, which means last in, first out. A queue is the opposite. It is like a line of people at a checkout, the first person to join the line is the first one served. That rule is called FIFO, which means first in, first out. Our job is to build a stack but only use queues as the storage. The trouble is that a queue serves from the front and a stack needs the newest item to come out first, so we have to do a little shuffling to make the queue behave like a stack. The neat trick is to use just one queue. Every time we add a new item, we slide all the older items around behind it so the newest item ends up at the front of the line. That way, when we take from the front (which is what a queue does), we get the newest item, exactly like a stack. This makes adding a bit slow, but taking and peeking are instant.
Signals to notice
Brute force first
No simpler alternative — you must simulate with the available structure. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Two queues: on push, enqueue to q2, then move all elements from q1 to q2, then swap q1 and q2. This makes push but pop/top. Or make pop costly instead. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on ops=["MyStack","push","push","top","pop","empty"], args=[[],[1],[2],[],[],[]]
push(1): append → queue=[1]; rotate 0 times → queue=[1] push(2): append → queue=[1,2]; rotate 1 time: popleft 1, append 1 → queue=[2,1] top(): return queue[0] = 2 (queue unchanged [2,1]) pop(): popleft → returns 2; queue=[1] empty(): len(queue)=1 → return false Output = [null, null, null, 2, 2, false]
What must stay true
After each push, q1 always has elements in stack order (newest first). The re-enqueueing step reverses the order so that the front of q1 is the top of the stack. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
push(x):
queue.append(x)
repeat (len(queue) - 1) times:
queue.append(queue.popleft()) # rotate newest to front
pop(): return queue.popleft()
top(): return queue[0]Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Making both push and pop costly — choose one. Costly push means every push rearranges; costly pop means every pop rearranges. Pick based on which operation is more frequent. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.