Quick revision
The short answer
A queue built from two stacks is a stacks and queues problem solved by lazy pouring. New elements go onto an in stack, dequeues pop from an out stack, and only when out is empty do we pour all of in into out, which reverses them into queue order. Every operation is amortised O(1) and the space is O(n).
The solution
What it costs
| Design | enqueue | dequeue | n dequeues in a row |
|---|---|---|---|
| One stack, dig down and put back | O(1) | O(n) | O(n^2) |
| Two stacks, pour only when out is empty | O(1) | amortised O(1) | O(n) |
What to remember
We built a queue from two stacks by giving them fixed jobs: in receives every new element, out serves the oldest one from its top, and we pour all of in into out only when out is empty, which reverses the elements into queue order. Each element moves across once, so every operation is amortised O(1) and the space is O(n). The clue to remember is a request for one order from a structure that gives the opposite one: pouring a stack into another reverses it, and doing it lazily keeps it cheap.
1What it means to build a queue out of two stacks
Picture two everyday things. The first is a pile of plates in a canteen kitchen. A clean plate is always put on top of the pile, and whoever needs a plate takes the top one, never one from the middle. That pile is a stack. Putting a plate on top is called push, and taking the top plate off is called pop. The plate that went on last comes off first, which is why a stack is described as last in, first out.
The second picture is a line of people at a ticket counter. A newcomer joins at the back, and the person served is always the one at the front, who has waited longest. That line is a queue. Joining at the back is called enqueue, and being served at the front is called dequeue. Here the first to arrive is the first to leave, so a queue is first in, first out.
The question asks us to build a queue, with enqueue, dequeue, peek to look at the front without removing it, and isEmpty, while storing the elements only in stacks. That sounds like a contradiction, but it is smaller than it looks. The whole solution rests on one fact you can check with two piles of plates on a table, and we will find that fact by hand.
Let us do the smallest example on paper. We enqueue 1, then 2, then 3, and then dequeue once. A queue must hand back 1, because 1 arrived first. But if we push 1, 2 and 3 onto one stack, 3 sits on top and 1 is buried at the bottom. That gap between the 1 we must return and the 3 a stack offers is the entire difficulty. For the rest of the article we use a longer sequence: enqueue 1, 2 and 3, dequeue, enqueue 4, dequeue, peek, dequeue, dequeue, and finally isEmpty. The right answers are 1, 2, 3, 3, 4 and true.
The queue is drawn as a line, front on the left. A stack holding the same three would have 3 on top.
- queue gives
- 1 first
- a stack gives
- 3 first
1We enqueue 1, then 2, then 3. A queue must hand back 1 first, because it arrived first, but a stack would hand back 3.
What to assume
- What should dequeue do on an empty queue?
- We throw
NoSuchElementException, as Java's own collections do. - Can enqueues and dequeues come in any mixed order?
- Yes.
- What may we use?
- Only stack operations, push, pop, peek and
isEmpty, on two stacks. In Java, theArrayDequeclass serves as the stack. - And what cost is expected?
- Each operation should take constant time on average.
A careful candidate settles a few details before writing code. What should dequeue do on an empty queue? We throw NoSuchElementException, as Java's own collections do. Can enqueues and dequeues come in any mixed order? Yes, and that is what makes the design interesting. What may we use? Only stack operations, push, pop, peek and isEmpty, on two stacks. In Java, the ArrayDeque class serves as the stack. And what cost is expected? Each operation should take constant time on average, an idea we will make precise later.
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 a problem about turning one order into another
On a first reading most of us think of the stacks as containers and wonder where to put each element. We push everything onto one stack, see that 3 comes out first, and feel stuck, because a stack only ever offers its top. It is not a trick; the question quietly tells us what to do, if we read its words one at a time.
The first clue is the phrase two stacks. One stack can produce only one order, newest first. If one stack were enough, the question would not give us a second. A second stack suggests that elements will move from one to the other, and that the move does something useful.
The second clue is the word queue. We are asked for the oldest element first, which is the exact opposite of what a stack gives. When a question wants one order from a structure that naturally gives the reverse order, think about reversing. So what happens when you lift plates one by one off a pile and set each on a second pile? The plate that was at the bottom ends up on top. Moving a stack onto another stack reverses it, and reversing the newest-first order gives oldest-first, which is queue order.
These clues place the problem in the stacks and queues family of patterns, where we build one of these structures from the other or use their orders to solve something else. The rule to carry to new problems has two halves. Popping everything from one stack onto another reverses the order, so two reversals bring back the original order. And when a move is expensive, make it only at the moment you cannot avoid it. That second half is called laziness, and it is what makes this design fast.
Some related problems look similar but work differently. A stack built from queues is the mirror question, but a queue never reverses anything when you move its elements, so one of its operations must rotate the whole queue every time and costs O(n). A stack that also reports its minimum uses two stacks kept in step, but nothing ever moves between them. And a circular array is the usual way to build a queue, but this question rules out arrays, so it is not the answer here.
3The honest first attempt, digging to the bottom on every dequeue
The first design anyone would make keeps all the elements in one stack, called main, with the newest on top. enqueue is simply a push. For dequeue, the oldest element sits at the bottom, so we lift off everything above it onto a second stack, called temp, take the bottom element, and then pour temp back so that main looks the way it did before. It is what you would do with real plates. A design that does the obvious thing without any cleverness is called a brute force, and it is a good start, because it is plainly correct.
Let us run it by hand. After enqueue 1, 2 and 3, main holds 1 at the bottom and 3 on top. To dequeue, we pop 3 and push it onto temp, then pop 2 and push it onto temp, so temp holds 3 at the bottom and 2 on top. Now 1 is the only element in main; we pop it and return it. Finally we pop 2 and 3 off temp and push them back onto main, which again holds 2 at the bottom and 3 on top.
main holds the queue with the newest on top. temp is used only while we dig. Bottom on the left, top on the right.
- operation
- dequeue starts
1After enqueue 1, 2 and 3, main holds all three with 3 on top. The oldest element, 1, is at the bottom.
- operation
- dig down
- moved so far
- 2
2To reach 1 we pop 3 and then 2 and push them onto temp. temp now holds 2 on top of 3, oldest first.
- returns
- 1
- moved so far
- 2
3We pop 1 from main and return it. Look at temp: 2 is on top, exactly the element the next dequeue wants.
- operation
- put back
- moved so far
- 4
4The first attempt now pours temp back into main, so main again has the newest on top. Two more moves.
- operation
- second dequeue
- moved so far
- 5
5The next dequeue digs again, moving 3 back onto temp to reach 2. It redoes the very moves we just undid. This is the waste.
Now let us count. With 3 elements, that dequeue made 2 moves down, 1 pop, and 2 moves back, five steps. With k elements it is about 2k moves. If we enqueue n elements and then dequeue them all, the dequeues cost about 2n, then 2(n - 1), and so on, which adds up to roughly n times n. When the work grows like n times n we write O(n^2), read as order n squared.
So where is the waste? Look at the third frame of the picture. Right after we took 1, temp held 2 on top of 3, oldest on top, exactly the order the next dequeue needs. Then we poured it all back, and the next dequeue dug through main again, moving 3 back onto temp to reach 2. Every dequeue throws away the useful order the previous one created.
A beginner reasonably asks why we put the elements back at all. The answer is a worry: if 2 and 3 stay in temp, where would a newly enqueued 4 go, and would it spoil the order? That worry is fair, and the next section shows it has a simple answer.
4From the wasted pouring to the lazy two-stack queue
Start from the waste. After digging, the second stack held the remaining elements oldest on top, ready to be served. So let it keep them. We give the two stacks permanent jobs and names to match. The stack called in receives every new element, newest on top, just like main did. The stack called out serves dequeues, and it always keeps the oldest element on top.
Now the worry from the last section. If out still holds 2 and 3 and someone enqueues 4, why not push 4 onto out? Let us try it and see. out holds 3 at the bottom and 2 on top. Pushing 4 puts 4 on top of 2, so the next dequeue would return 4 before 2, which is wrong. So a new element never goes onto out. It always goes onto in, where it waits its turn behind everything already in out.
That raises a second question, which is when elements should move from in to out. Suppose out still holds 2 and we pour the in stack, holding 4, into out anyway. Then 4 lands on top of 2 and comes out first, wrong again. So we pour only when out is completely empty, and when we pour, we pour all of in. Lifting every element off in reverses it, so the oldest element in in ends up on top of out.
Why is this always correct? Keep three facts in mind. Everything in out arrived before everything in in, because elements move across only in one batch, and only when out has run dry. Inside out, the oldest element is on top, because the pour reversed newest-first into oldest-first. Inside in, elements simply wait in arrival order. Put together, the top of out, after a pour if out was empty, is always the oldest element in the whole queue, so popping it is a correct dequeue and reading it is a correct peek.
Why is it fast, when a single pour can move many elements? Follow one element through its life instead of one operation. It is pushed onto in once, popped from in once, pushed onto out once, and popped from out once. Four stack operations, however the enqueues and dequeues are mixed. So n operations do at most about 4n stack operations in total, as if each enqueue dropped a few coins in a jar that the occasional pour later spends. When the total over a whole sequence is O(n), we say each operation costs amortised O(1), meaning constant on average over the sequence, even though one particular call may be slow.
The mistake a beginner is most tempted to make is to pour on every dequeue, or to pour whenever in is not empty. It feels tidy, but it brings back the waste and breaks the order when out still holds older elements. The rule is short: pour only when out is empty.
5Watching the two stacks through the whole sequence
The picture plays our sequence on the real design. Each row is one stack, named in its first box, with the bottom on the left and the top on the right. Empty places are dimmed. Watch for two things: elements cross from in to out only when out is empty, and each element crosses exactly once.
The panel beside each drawing names the operation and what it returns.
Each row is one stack, named in its first box. The bottom of a stack is on the left and its top is the last filled box on the right.
- operation
- enqueue 1
- returns
- nothing
1enqueue 1 pushes 1 onto in. It is the only element, so it is both the oldest and the newest.
- operation
- enqueue 2
- returns
- nothing
2enqueue 2 pushes 2 onto in, on top of 1. The newest element is on top of in, as it always will be.
- operation
- enqueue 3
- returns
- nothing
3enqueue 3 pushes 3 onto in. The oldest element, 1, is now buried at the bottom, where a stack cannot reach it.
- operation
- dequeue
- pour
- 3 elements moved
- top of out
- 1
4dequeue finds out empty, so it pours the in stack into out: pop 3 and push it, then 2, then 1. The order flips, and 1 lands on top of out.
- operation
- dequeue
- returns
- 1
- top of out
- 2
5Now dequeue pops the top of out and returns 1, the element that arrived first. 2 is now on top, next in line.
- operation
- enqueue 4
- returns
- nothing
6enqueue 4 goes onto in, never onto out. out still holds 2 and 3 in queue order, and 4 waits behind them.
- operation
- dequeue
- pour
- none, out was not empty
- returns
- 2
7dequeue sees that out is not empty, so it does not pour. It pops 2 from out and returns it. No element moved, and 3 is now on top.
- operation
- peek
- pour
- none
- returns
- 3
8peek also checks out first. out holds 3, so peek returns 3 and leaves it where it is.
- operation
- dequeue
- returns
- 3
- queue empty?
- no, 4 waits
9dequeue pops 3 from out and returns it. out is empty now, but in still holds 4, so the queue is not empty.
- operation
- dequeue
- pour
- 1 element moved
- top of out
- 4
10The next dequeue finds out empty again, so it pours. Only one element waits in in, so 4 alone moves across.
- operation
- dequeue
- returns
- 4
- order so far
- 1, 2, 3, 4
11dequeue pops 4 from out and returns it. Every element left in the order it arrived: 1, 2, 3, 4.
- operation
- isEmpty
- returns
- true
- moves in all
- 4
12
isEmptychecks both stacks. Both are empty, so it returns true. Each element crossed from in to out exactly once.
Let us read the important frames back. In the fourth frame the first dequeue finds out empty, so it pours: 3 moves first, then 2, then 1, and the row for out reads 3, 2, 1 from bottom to top. The order has flipped, and 1, the oldest, is on top. The next frame pops it and returns 1.
The sixth frame is the one the first attempt was afraid of. 4 arrives while 2 and 3 are still waiting in out. It goes onto in and stays there, untouched, while the next two operations serve 2 and then peek at 3, with no pouring at all.
Only in the tenth frame is out empty again, and only then does 4 cross over, alone. Count the crossings over the whole picture: 1, 2 and 3 crossed once in the first pour and 4 crossed once in the second, four moves for four elements.
6The complete Java program
Here is the full class. Two ArrayDeque objects act as the stacks, used only through push, pop, peek and isEmpty. A private helper, moveIfNeeded, does the lazy pour, so dequeue and peek can share it. main runs our sequence, checks isEmpty, and shows what happens on an empty queue.
Let us read it in the order a call runs. enqueue is one line: push onto in. It never looks at out.
dequeue first calls moveIfNeeded. Inside it, the test out.isEmpty() is the heart of the design. If out still has elements, the method does nothing, so a dequeue in the middle of a batch costs one pop. If out is empty, the while loop pops each element off in and pushes it onto out until in is empty, which reverses them into queue order.
Back in dequeue, we check out.isEmpty() again. If it is still empty after the pour, then in was empty too, the whole queue is empty, and we throw NoSuchElementException with a clear message rather than returning a made-up value. Otherwise out.pop() returns the oldest element. peek follows the same steps but calls out.peek(), which reads the top without removing it.
isEmpty checks both stacks. A tempting slip is to check only out, but after the third dequeue in our sequence, out was empty while 4 still waited in in, and the queue was not empty. main prints 1, 2, 3, 3, 4, true and the exception message, as the comments show.
7How much it costs, and the cases at the edges
Let us count on the example first. The two pours moved four elements in all, and every other operation did a single push, pop or peek. Each element was pushed onto in, popped from in, pushed onto out and popped from out, sixteen stack operations for four elements, four each.
In general, enqueue is always O(1). dequeue and peek are O(1) when out has elements and O(k) when they pour k elements, but since each element is poured at most once, the total for n operations is O(n), so every operation is amortised O(1). The space is O(n), because the two stacks together hold each element exactly once.
| Design | enqueue | dequeue | n dequeues in a row |
|---|---|---|---|
| One stack, dig down and put back | O(1) | O(n) | O(n^2) |
| Two stacks, pour only when out is empty | O(1) | amortised O(1) | O(n) |
The edge cases are handled by the code we already have. A dequeue or peek on an empty queue pours nothing, finds out still empty, and throws NoSuchElementException. A queue with a single element pours it on the first dequeue and hands it straight back.
One situation calls for a different tool. If a single call must never be slow, for example in a real-time system that cannot pause for a pour of a million elements, amortised O(1) is not enough. Then we would use a circular array queue, where every operation is O(1) in the worst case.
8Follow-up questions
How would you build a stack from queues instead?
With one queue, push adds the new element at the back and then rotates the queue, removing and re-adding each of the other size - 1 elements, so the newest element comes round to the front. pop and top then simply read the front. Moving elements through a queue never reverses their order, so there is no lazy trick that makes both operations cheap. push costs O(n) and pop costs O(1), or the other way round if we rotate during pop instead.
What exactly is the difference between amortised O(1) and O(1) in the worst case?
Worst-case O(1) promises that every single call is fast. Amortised O(1) promises something weaker but still useful: any sequence of n calls costs O(n) in total, so the average per call is constant, even though one particular call may be slow. In our queue, one dequeue may pour n elements, but those n elements were each enqueued cheaply first, so the total stays linear. ArrayList.add is another everyday example, because an occasional resize copies the whole array.
Can peek avoid pouring?
Yes, with one extra variable. When an element is pushed onto an empty in, we remember it as front, because it is the oldest element in in. peek then returns out.peek() if out has elements, and front otherwise, without moving anything. dequeue still pours lazily as before. This does not change the amortised cost, but it makes peek O(1) in the worst case, which some interviewers ask for as a follow-up.
9Conclusion
We built a queue from two stacks by giving them fixed jobs: in receives every new element, out serves the oldest one from its top, and we pour all of in into out only when out is empty, which reverses the elements into queue order. Each element moves across once, so every operation is amortised O(1) and the space is O(n). The clue to remember is a request for one order from a structure that gives the opposite one: pouring a stack into another reverses it, and doing it lazily keeps it cheap.
Open with
Let me confirm the operations first: enqueue, dequeue, peek and isEmpty, in any mixed order, using only push, pop, peek and isEmpty on two stacks, and dequeue on an empty queue throws NoSuchElementException.
Then, if they want more
A stack gives newest first and a queue needs oldest first, so the key fact is that popping one stack onto another reverses the order. The simple design keeps one stack, digs down to the bottom on every dequeue and puts everything back, which is O(n) per dequeue and O(n^2) for n dequeues. I will avoid putting things back.
I keep an in stack for new elements and an out stack that serves dequeues with the oldest on top. enqueue pushes onto in. dequeue and peek first check out; only if it is empty do I pour all of in into out, which puts the oldest element on top.
New elements never go onto out, and I never pour while out still has elements, because both would put a newer element above an older one. Each element is pushed and popped at most twice in its life, so any sequence of n operations is O(n), which is amortised O(1) per operation, with O(n) space. isEmpty checks both stacks.
About this answer
- Last updated
- 14 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 18 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 "Implement a queue using two stacks.": https://scrivio-interview-library.netlify.app/data-structures/solutions/implement-a-queue-using-two-stacks-edc634/