Quick revision
The short answer
Building a stack from queues is a stacks and queues problem in which one structure imitates another. We keep one queue whose front is always the top of the stack: push adds the new item at the back and then moves every older item from the front to the back, so pop and top become a plain poll and peek. Push costs O(n), pop and top cost O(1), and the space is O(n).
The solution
What it costs
| Approach | push | pop and top | Queues used |
|---|---|---|---|
| Two queues, dig out on pop | O(1) | O(n) | 2 |
| One queue, rotate on push | O(n) | O(1) | 1 |
What to remember
We built a stack using only queue operations. The two-queue brute force keeps arrival order and digs out the newest item on every pop, moving n - 1 items each time. Keeping one queue in stack order instead, by offering each new item and rotating the older items behind it, makes push O(n) and pop and top O(1). Some operation must pay, because a queue only shows its oldest item, and we choose which one by the workload. The clue to remember is one container imitating another: compare the two orders, and ask what the allowed operations can do to an order. A queue can rotate but never reverse.
1What a stack must do, and what a queue allows
Think of a pile of plates in a kitchen. You put a clean plate on top, and when you need one you take the plate on top, which is always the one put there last. That is a stack. Now think of a line of people at a ticket counter. People join at the back, and the person served is the one at the front, who has waited longest. That is a queue. Our task is to make a line of people behave like a pile of plates.
Let us name the two orders one at a time. A stack is last in, first out: the item added most recently comes out first. Its operations are push, which adds an item on top, pop, which removes and returns the top item, top, which only looks at it, and isEmpty. A queue is first in, first out: the item that has waited longest comes out first.
Now the rule of the game. We may store the items only in a queue, and touch them only through queue operations: offer adds at the back, poll removes from the front, peek reads the front, and size and isEmpty tell us how many there are. We may not look into the middle or take from the back. Java's ArrayDeque could do that, but we will hold it as a plain Queue so the compiler stops us from cheating.
Let us do the example by hand. We push 1, then 2, then 3. A stack must now pop 3, the last one in. After that, top must show 2 without removing it. Then we push 4, and three pops must return 4, 2 and 1, after which the stack is empty. The picture shows the problem in one glance: the same three pushes leave a queue that would hand back 1, when the stack must hand back 3.
Both rows are read from the front on the left. A queue hands back the oldest item; the stack we must build hands back the newest.
1After adding 1, 2 and 3, a plain queue reads 1 2 3 and would hand back 1 first. The stack we want reads 3 2 1 from the top and must hand back 3 first.
What to assume
- What should pop do on an empty stack?
- We throw
NoSuchElementException, as Java's own collections do. - May we use one queue or two?
- Either. And we assume a single thread.
A careful candidate asks a few questions first. What should pop do on an empty stack? We throw NoSuchElementException, as Java's own collections do. Will pushes or pops be more frequent? This matters more than it seems, because we will find that one of them has to be slow, and we would like the rarer one to pay. May we use one queue or two? Either; we will see both. And we assume a single thread.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise the pattern of one structure imitating another
A beginner's first reaction is often to look for a queue method that takes from the back, and there is none. The second reaction is to feel that the problem is impossible, since a queue always gives the oldest item and we want the newest. It is not impossible. We simply have to be patient with the queue and move items around until the newest one is at the front.
So let us read the question slowly and take its clues one at a time. The first clue is the word stack. It tells us what must come out: always the newest item. Whatever we build, the newest item must somehow be reachable, either by keeping it at the front or by digging it out when asked.
The second clue is the phrase only queue operations. It tells us what we may do to an order. Here is the important observation. A queue never changes the order of the items it holds; what goes in comes out in the same sequence. But it can rotate them. If we poll the front item and offer it straight back, the item that waited longest walks to the back of the line, and everyone else moves up one place. Rotation is the one tool a queue gives us.
Together these clues point to the stacks and queues family, in its design form: implement one container using only the operations of another. The method is always the same. Write down the order each container keeps, write down what the allowed operations can do to an order, and ask how those operations can produce the order you need. The general rule to carry to new problems is to compare the two orders first and the method names second.
The mirror problem, a queue built from two stacks, looks similar but works differently, and mixing them up is a common mistake. A stack reverses order, and two reversals cancel, so pouring one stack into another produces queue order cheaply. Pouring one queue into another reverses nothing, because a queue keeps order, so that trick does not carry over here, and one of our operations will stay slow whatever we do.
3The honest first attempt, two queues and a costly pop
The brute force, the first version that works, keeps the items in arrival order, exactly as a queue likes them, so push is a single offer. The newest item then sits at the back of the queue, where we cannot reach it. So pop digs it out: it moves every item except the last one into a second, helper queue, polls the last one as the answer, and then swaps the names of the two queues, so the helper, now holding the rest in their original order, becomes the main queue.
Let us do one pop by hand, which the picture below also shows. After pushing 1, 2 and 3, the main queue reads 1 2 3. Pop moves 1 to the helper, then 2, so only 3 is left; it polls 3 and returns it, and the helper, holding 1 2, becomes the main queue.
The cells are the main queue, front on the left. The helper queue is shown on the right. Everything but the newest item has to move.
- helper
- empty
- moved
- 0
1After
push(1),push(2)andpush(3), the main queue holds 1 2 3 in arrival order. The newest item, 3, is at the back, where a queue cannot reach.- helper
- 1
- moved
- 1
2
pop()polls the front item, 1, and offers it to the helper queue, because 1 is not the newest item.- helper
- 1 2
- moved
- 2
3It moves 2 across as well. Now only 3 is left in the main queue, so 3 is the newest item and the answer.
- helper
- empty
- moved
- 2
- returns
- 3
4We poll 3 to return it, and swap the two queues, so the main queue is now 1 2. Every pop repeats this whole journey.
Now let us count. Push is one offer, O(1), meaning constant time whatever the size. But a pop on a stack of n items moves n - 1 items before it can answer, so pop is O(n), meaning its work grows in step with n. top is just as slow, because it too must reach the back. A stack of a thousand items moves 999 items on every pop.
So where is the waste? Look at the last frame. After moving everything, the main queue reads 1 2 again, in arrival order, the same order it had before, minus one item. The next pop will move them all again, and if the caller asks for top and then pop, the same items are moved twice. We already knew the stack order at the moment each item arrived, and we keep rediscovering it.
4Getting to one queue that is always in stack order
If we know where an item belongs the moment it arrives, the sensible thing is to put it there once, at push time, instead of digging for it at every pop. So let us make a promise: the queue, read from front to back, will always list the stack from top to bottom. If we can keep that promise, pop is just poll, top is just peek, and isEmpty is the queue's own isEmpty, all O(1).
Push is where we must keep the promise. A new item x has to end up at the front, but offer puts it at the back. This is where rotation helps. After offering x, we poll the front item and offer it at the back, and we do this once for every item that was there before x, which is size - 1 times. Each rotation takes the oldest of the waiting items and puts it behind x.
Now the question a beginner should ask. Will all this rotating not scramble the older items? Let us try it and see. Suppose the queue reads 2 1, so 2 is on top. We push 3 by offering it: 2 1 3. The first rotation moves 2 to the back: 1 3 2. The second moves 1 to the back: 3 2 1. The older items left the front in the order 2 then 1 and joined the back in the same order, so their order is unchanged; they have simply walked round behind 3. That is the promise kept.
Why size - 1 rotations and not size? If we rotated size times, x itself would be polled and offered too, and the queue would be back to 2 1 3 with x at the back. One rotation for each older item is exactly enough to bring x to the front.
Why is the whole design correct? The promise holds for an empty queue. Push keeps it, as we just saw. Pop and top only touch the front, which by the promise is the newest item, and removing it leaves the rest still in stack order. So the promise holds after every call. Push now costs O(n), and that is unavoidable here: a queue only ever shows its oldest item, so some operation must pay to bring the newest one forward. We choose to make push pay, because most programs read the top of a stack more often than they push.
5Watching the queue call by call
The picture plays the example sequence on our single queue. Each frame shows the queue, front on the left, after one line of code runs: an offer, a single rotation, or a pop or top. The item just offered is highlighted, the item that has just walked to the back is marked as compared, and the panel says which call we are in and how many rotations it has done.
The cells are the queue, front on the left. A new item joins at the back, then each older item walks from the front to the back behind it.
- call
- push(1)
- rotations
- 0
1
push(1)offers 1 into the empty queue. The queue has one item, so there is nothing older to rotate, and 1 is both the front and the top.- call
- push(2)
- rotations
- 0
2
push(2)first offers 2 at the back. The queue reads 1 2, which has the newest item in the wrong place.- call
- push(2)
- rotations
- 1
3Now one rotation: poll the front, 1, and offer it at the back. The queue reads 2 1, so the newest item is at the front again.
- call
- push(3)
- rotations
- 0
4
push(3)offers 3 at the back. The queue reads 2 1 3. There are two older items, so we will rotate twice.- call
- push(3)
- rotations
- 1
5The first rotation moves 2 from the front to the back. The queue reads 1 3 2.
- call
- push(3)
- rotations
- 2
6The second rotation moves 1 to the back. The queue reads 3 2 1, which is the stack from top to bottom.
- call
- pop()
- returns
- 3
7
pop()is a plain poll. It removes 3 from the front and returns it, the last item pushed, and the queue reads 2 1.- call
- top()
- returns
- 2
8
top()is a plain peek. It returns 2 without removing it, so the queue still reads 2 1.- call
- push(4)
- rotations
- 0
9
push(4)offers 4 at the back, so the queue reads 2 1 4. Two older items sit in front of it.- call
- push(4)
- rotations
- 1
10The first rotation moves 2 behind 4. The queue reads 1 4 2.
- call
- push(4)
- rotations
- 2
11The second rotation moves 1 behind 2. The queue reads 4 2 1, so 4 is on top and the older items keep their order.
- call
- pop()
- returns
- 4
12
pop()polls 4 from the front and returns it. The queue reads 2 1 again, ready for the last two pops.
Let us read the important frames back. push(3) is shown in three frames. The offer leaves 2 1 3, with the new item at the back. The two rotations then walk 2 and 1, in that order, round behind 3, and the queue reads 3 2 1, which is exactly the pile of plates from the top.
pop() and top() are single frames, because they are single queue operations: poll takes 3 from the front, and peek reads 2 without removing it. push(4) repeats the push(3) story, offer and then two rotations, and leaves 4 2 1. After the last frame, the two remaining pops poll 2 and then 1, and isEmpty returns true, so the whole sequence came out last in, first out.
6The complete Java program
Here is the full class. It holds one ArrayDeque, but only through the Queue interface, so only offer, poll, peek, size and isEmpty are available. The main method runs the example sequence and finally pops an empty stack to show the error message. The comment on each line shows what it prints.
Let us read push in the order it runs. queue.offer(x) puts the new item at the back. Then the for loop runs from 1 while i < queue.size(), so it runs size - 1 times, once for each older item. Notice that the size includes x, which is why the loop starts at 1. Inside, queue.offer(queue.poll()) takes the front item and puts it at the back in one line. When the loop ends, x is at the front.
pop first checks isEmpty, because poll on an empty queue returns null, and unboxing null into an int would throw a confusing NullPointerException. Throwing NoSuchElementException with a clear message is kinder to the caller. Then it polls the front, the newest item. top does the same check and peeks instead of polling. isEmpty simply asks the queue.
Declaring the field as Queue rather than ArrayDeque is a small but deliberate choice. It means the compiler refuses calls such as pollLast or push, which an ArrayDeque has, so we cannot break the rule of the game by accident.
7How much it costs, and the cases at the edges
Let us count on the example first. push(1) did one offer and no rotations, push(2) one rotation, push(3) two, and push(4) two again, because the stack held two items when 4 arrived. In general a push onto a stack of n items does one offer and n rotations, so push is O(n). pop, top and isEmpty each do one queue operation, so they are O(1).
The queue holds each item exactly once, so the space is O(n) for n items, the same as any stack. Compared with the two-queue version, a push followed by one pop does the same amount of moving, but every later read is free, and calling top no longer moves anything.
| Approach | push | pop and top | Queues used |
|---|---|---|---|
| Two queues, dig out on pop | O(1) | O(n) | 2 |
| One queue, rotate on push | O(n) | O(1) | 1 |
Popping or peeking an empty stack throws NoSuchElementException with the message stack is empty, which the last line of main prints. Pushing onto an empty stack offers the item and rotates zero times, because the loop condition 1 < 1 is false straight away. A stack of one item behaves the same way: its single item is both the front of the queue and the top of the stack.
One quieter edge case concerns nulls. ArrayDeque refuses null items, and poll uses null to mean empty, so a stack that must store nulls would need a different queue, such as LinkedList. Our stack stores int values, so the question does not arise.
8Follow-up questions
How would you build a queue from two stacks?
Keep an in stack for new items and an out stack for removals. To add, push onto in. To remove or peek, first check out; if it is empty, pop every item from in and push it onto out. That pouring reverses the order, so the oldest item ends up on top of out, ready to be popped. Each item is poured at most once in its life, so every operation is O(1) on average, which we call amortized O(1). It works because a stack reverses and two reversals cancel, which is exactly what a queue cannot do.
Which version should you choose in practice?
Choose by the workload. If pops and tops are frequent, as in most uses of a stack, make push pay with the single rotating queue. If items are pushed in large bursts and rarely popped, the two-queue version, where push is cheap, does less work. Saying this trade-off aloud is often what the interviewer is waiting for, since neither version is better in every case.
Why can neither version make every operation O(1)?
A queue only ever shows us its oldest item. A stack must hand back the newest. So at some moment, the newest item has to travel past every older item to reach the front, and that journey is as long as the number of items. We can choose when it happens, at push or at pop, but not avoid it. The two-stack queue escapes this only because a stack can reverse, which a queue cannot.
9Conclusion
We built a stack using only queue operations. The two-queue brute force keeps arrival order and digs out the newest item on every pop, moving n - 1 items each time. Keeping one queue in stack order instead, by offering each new item and rotating the older items behind it, makes push O(n) and pop and top O(1). Some operation must pay, because a queue only shows its oldest item, and we choose which one by the workload. The clue to remember is one container imitating another: compare the two orders, and ask what the allowed operations can do to an order. A queue can rotate but never reverse.
Open with
So I need push, pop, top and isEmpty, using only offer, poll, peek, size and isEmpty on a queue, and pop on an empty stack should throw. The difficulty is that a stack returns the newest item while a queue only exposes the oldest.
Then, if they want more
A first version keeps items in arrival order, so push is a plain offer, and pop moves all but the last item into a helper queue, takes the last one, and swaps the queues. That makes pop and top O(n), and the same items move again on every pop.
Since a queue cannot reverse order but can rotate it, I would rather fix the order once, at push time. I keep one queue whose front is always the top of the stack.
To push x, I offer it at the back and then poll and re-offer the front size minus one times, which walks every older item behind x in its original order. Now pop is poll, top is peek, and isEmpty is isEmpty, all O(1), while push is O(n).
The invariant is that the queue front to back lists the stack from newest to oldest. Both cannot be O(1), because the newest item must travel past the older ones at some point, so I make push pay, since pops are usually frequent. Space is O(n), and pop or top on an empty stack throw NoSuchElementException.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 73 times in that collection. How it is counted
- Official documentation
- ArrayDeque (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Build a stack using only queue operations.": https://scrivio-interview-library.netlify.app/data-structures/solutions/build-a-stack-using-only-queue-operations-719160/