Scrivio Interview library
Data structure basicsStacks, queues and heapsReported 53 times · 15 min read · updated 15 November 2026

How does a stack differ from a queue?

1A pile of plates and a line at a ticket counter

Think of a pile of clean plates in a kitchen. You put a washed plate on top of the pile, and when you need one, you take the top plate. You never pull one from the middle or the bottom. So the plate that went on last is the plate that comes off first. That is a stack, and its rule has a name, LIFO, which stands for last in, first out.

Now think of a line of people at a ticket counter. A newcomer joins at the back, and the person at the front is served first. Nobody pushes in, so the person who came first leaves first. That is a queue, and its rule is FIFO, first in, first out.

This question can feel bigger than it is, because books describe each structure with its own vocabulary. In fact a stack and a queue are alike in almost every way. Both keep items in the order they arrived, and both let us add an item and remove an item, one at a time. The only difference is which item comes out when we remove one.

The operations take their names from these pictures. Putting an item on a stack is called push, and taking the top item off is pop. Looking at the top without removing it is peek. For a queue, adding at the back is called enqueue, which Java calls offer. Removing from the front is called dequeue, which Java calls poll, and peek looks at the front.

Let us try both by hand with three letters. Push A, then B, then C onto a stack, and pop twice: we get C and then B, and A is left alone. Offer A, then B, then C to a queue, and poll twice: we get A and then B, and C is left waiting. Same three letters, same two removals, opposite answers. Keep these letters in mind, because the pictures and the Java below use them.

2How a stack is built inside an array

Inside a computer, the simplest home for a stack is an array, a row of numbered slots. We also keep one number, size, the count of items in the stack. size does a second job without any extra effort: it is the index of the first free slot, because items fill the slots from 0 upwards with no gaps.

So push writes the new item into slot size and then adds one to size. And pop does the reverse, in the reverse order: it takes one off size and then reads that slot, which holds the top item. Here is that tiny class, with an array of four slots so the picture stays small.

Step throughA stack inside an array of four slots

Each box is one slot of the array. The size pointer sits under the next free slot. Dimmed values are old copies that are out of play.

  1. 0123size
    operation
    new ArrayStack()
    returned
    -
    size
    0

    1A new ArrayStack has four empty slots and size 0. size is both the number of items and the index of the next free slot.

  2. A0123size
    operation
    push A
    returned
    -
    size
    1

    2push("A") writes A into slot size, which is 0, and then adds one, so size is 1. A is now the top.

  3. A0B123size
    operation
    push B
    returned
    -
    size
    2

    3push("B") writes into slot 1 and size becomes 2. Nothing already in the array moved.

  4. A0B1C23size
    operation
    push C
    returned
    -
    size
    3

    4push("C") writes into slot 2 and size becomes 3. The top is always the slot just below size.

  5. A0B1C23size
    operation
    pop
    returned
    C
    size
    2

    5pop() first takes one off size, making it 2, and then returns slot 2, which is C. C is still in the array but out of play.

  6. A0B1C23size
    operation
    pop
    returned
    B
    size
    1

    6pop() again makes size 1 and returns slot 1, B. The most recent item came out each time, which is last in, first out.

  7. A0D1C23size
    operation
    push D
    returned
    -
    size
    2

    7push("D") writes into slot size, which is 1, over the old B, and size becomes 2. The stack now holds A at the bottom and D on top.

Java
static class ArrayStack {
String[] items = new String[4];
int size = 0; // how many items; also the next free slot
void push(String x) { items[size++] = x; } // write on top, then grow
String pop() { return items[--size]; } // shrink, then read the old top
}

Look at the fifth frame. After pop returns C, the letter C is still sitting in slot 2. A beginner often expects pop to erase it, but there is no need. size now says the stack ends at slot 1, so slot 2 is out of play, and the next push simply writes over it, as D does over B in the last frame. Classes that store objects, such as ArrayDeque, also set the old slot to null so the garbage collector can free the object, but the idea is the same.

Why is the order inside pop important? items[--size] takes one off size before reading, because size points one past the top. If we read items[size] first, we would read an empty or old slot. That off by one slip is the most common mistake when writing a stack by hand.

Each push and each pop touches one slot and changes one number, whatever the size of the stack, so both take constant time, written O(1). When the array fills up, a growing stack copies its items into an array twice as large. That copy is slow, but it happens so rarely that the average cost of a push stays O(1), which is called amortized O(1). A stack can also be built from linked nodes, with the top as the head node.

3How a queue is built inside an array that wraps round

A queue on an array needs one more idea, because items leave from the front, not from the end where they were added. Here is the question a beginner naturally asks. Why not keep the front item in slot 0 and, after each removal, shift every other item one slot to the left? Let us count. With a thousand people in the line, each removal would move 999 items. The removal would cost O(n), growing with the length of the line, which throws away the whole point of a simple structure.

The trick is to move the markers instead of the items. We keep head, the index of the front item, and tail, the index of the next free slot. offer writes at tail and moves tail forward. poll reads at head and moves head forward. When either marker steps past the last slot, it goes round to slot 0, which is what the % sign does, the remainder after division, so (3 + 1) % 4 is 0. This arrangement is called a circular buffer, or a ring, because the end of the array joins back to its start like a running track.

Step throughA queue inside an array that wraps round

head points to the front item and tail to the next free slot. Both only move forward, wrapping from slot 3 back to slot 0.

  1. 0123headtail
    operation
    new RingQueue()
    returned
    -
    count
    0

    1A new RingQueue has four empty slots. head marks the front, tail marks the next free slot, and both start at slot 0.

  2. A0123headtail
    operation
    offer A
    returned
    -
    count
    1

    2offer("A") writes A at tail, slot 0, and moves tail to slot 1. A is both the front and the back.

  3. A0B123headtail
    operation
    offer B
    returned
    -
    count
    2

    3offer("B") writes into slot 1 and tail moves to 2. B joined behind A, like a person joining the back of a line.

  4. A0B1C23headtail
    operation
    offer C
    returned
    -
    count
    3

    4offer("C") writes into slot 2 and tail moves to 3. The queue holds A, B, C from front to back.

  5. A0B1C23headtail
    operation
    poll
    returned
    A
    count
    2

    5poll() reads the front, slot 0, and returns A, then moves head to slot 1. Nothing is shifted; only head moved.

  6. A0B1C23headtail
    operation
    poll
    returned
    B
    count
    1

    6poll() reads slot 1 and returns B, and head moves to slot 2. The oldest item came out each time, which is first in, first out.

  7. A0B1C2D3headtail
    operation
    offer D
    returned
    -
    count
    2

    7offer("D") writes into slot 3. tail is now at the end of the array, so (3 + 1) % 4 sends it round to slot 0.

  8. E0B1C2D3headtail
    operation
    offer E
    returned
    -
    count
    3

    8offer("E") writes into slot 0, over the old A, which nobody needed any more, and tail moves to 1. The queue is C, D, E.

  9. E0B1C2D3headtail
    operation
    poll
    returned
    C
    count
    2

    9poll() reads slot 2 and returns C, the oldest item left, and head moves to 3. The queue holds D then E, wrapped round the end of the array.

Java
static class RingQueue {
String[] slots = new String[4];
int head = 0, tail = 0, count = 0; // front, next free slot, how many
void offer(String x) {
slots[tail] = x; // join at the back
tail = (tail + 1) % slots.length; // step on, wrapping 3 -> 0
count++;
}
String poll() {
String x = slots[head]; // serve the front
head = (head + 1) % slots.length; // the next one is now the front
count--;
return x;
}
}

Follow the letters through the frames. The first three offers fill slots 0 to 2, and the two polls hand back A and then B, the oldest items, just as the line at the counter would. The interesting moment is the seventh frame. tail reaches the end of the array, and instead of reporting that the array is full, it wraps to slot 0, where A used to be. That slot is free because A left long ago, so E can safely go there.

In the last frame the queue holds D in slot 3 and E in slot 0. It looks broken, front at the right and back at the left, but read it starting from head and going round: D, then E. That is the right order. count says how many items are live. It is what tells a full ring from an empty one, because head equals tail in both cases; our small classes leave out the full and empty checks to stay short.

Each offer and each poll touches one slot and moves one marker, so both are O(1), with no shifting at all. A queue can also be built from linked nodes, keeping a reference to the head node for removing and the tail node for adding. Java's ArrayDeque is a circular buffer that grows when full, which is why it can serve as a stack and as a queue.

4The differences side by side

Now we can put the two structures next to each other. Read the first row carefully, because the order of removal is the one real difference, and every other row follows from it.

Stack versus queue
AspectStackQueue
Which item leaves nextthe newest, LIFOthe oldest, FIFO
Everyday picturea pile of platesa line at a ticket counter
Ends usedone end for adding and removingadd at the back, remove at the front
Main operationspush, pop, peekoffer, poll, peek
Cost of add and removeO(1), amortized when the array growsO(1), amortized when the array grows
Built on an arraya size countera ring with head and tail
Typical usesundo, call stack, brackets, depth first searchscheduling, buffers, breadth first search
In JavaArrayDeque with push and popArrayDeque with offer and poll

Notice that neither structure lets us reach an item in the middle. That restriction is not a weakness. Because only one end, or two fixed ends, can change, every operation is cheap and the order of removal is always predictable, which is exactly what the algorithms that use them depend on.

5Watching a stack match brackets

To see why the stack's rule is useful, let us give it a real job. We want to check whether the brackets in a string such as {[()]} are balanced, meaning every opener has a closer of the same kind, and pairs are properly nested. The key fact is that a closer must match the most recent opener that is still waiting. The newest waiting item is exactly what a stack hands back. So we push every opener, and at every closer we pop the top and check that it is the matching kind.

In the picture the string is drawn as a row of cells, with i under the character being read. The panel shows the stack with its top first.

Step throughA stack checking the brackets in {[()]}

The stack, shown with its top first, holds the openers still waiting for their closers.

  1. {0[1(2)3]4}5i
    character
    {
    action
    push
    stack, top
    {

    1The first character, {, is an opener, so we push it. The stack now holds one unmatched opener.

  2. {0[1(2)3]4}5i
    character
    [
    action
    push
    stack, top
    [ {

    2[ is an opener too, so it goes on top of {. The newest unmatched opener is always on top.

  3. {0[1(2)3]4}5i
    character
    (
    action
    push
    stack, top
    ( [ {

    3( is pushed on top. Three openers wait, and the one opened last must be closed first.

  4. {0[1(2)3]4}5i
    character
    )
    action
    pop
    stack, top
    [ {

    4) is a closer. We pop the top, (, and it matches, so the innermost pair is complete.

  5. {0[1(2)3]4}5i
    character
    ]
    action
    pop
    stack, top
    {

    5] pops the new top, [, which matches. Each closer is checked against the most recent opener only.

  6. {0[1(2)3]4}5i
    character
    }
    action
    pop
    stack, top
    empty

    6} pops {, which matches, and the stack is empty. Every opener was closed in the right order, so the answer is true.

The middle frames show the rule at work. After three pushes the stack holds (, [ and {, top first, and the closers arrive in exactly the reverse order. Each pop finds its partner, and at the end the stack is empty, so nothing was left unclosed.

Now try ([)] by hand. We push ( and then [. The next character is ), so we pop the top, which is [, and it does not match. The answer is false, and the stack found the problem at the exact character where the nesting went wrong. Would a queue work here? Let us see. A queue would hand back (, the oldest opener, at the first closer, and in {[()]} it would compare ) with {, which is wrong. The problem needs the newest item, so it needs a stack.

6How to recognise which one a problem needs

In an interview the question is rarely which structure you prefer; it is which one this problem needs. The words of the problem usually tell us, if we read them for order.

A stack fits whenever the most recent unfinished thing must be dealt with first. Words such as undo, matching, nested, most recent, backtrack, or evaluate an expression are the clues. The Java call stack is the classic case: each method call is pushed, and a return pops back to the caller, the most recent one. Depth first search, which goes as deep as it can along one path before backing up, uses a stack for the same reason. A special kind, the monotonic stack, whose values only rise or only fall from bottom to top, answers next greater element questions in one pass.

A queue fits whenever fairness or arrival order matters. Words such as in the order they arrived, level by level, fewest steps, or process in rounds are the clues. A printer or a pool of worker threads hands out jobs in arrival order. Breadth first search uses a queue so that every node one step away is handled before any node two steps away, which is why it finds the shortest path in a graph without weights. A useful thing to notice is that the same search loop becomes depth first with a stack and breadth first with a queue.

When a problem needs both ends, such as keeping the largest value in every sliding window, the answer is a deque, short for double ended queue, which can add and remove at either end. And when a problem needs the smallest or largest item first, whatever its arrival time, neither fits, and the tool is a priority queue.

7Using a stack and a queue in Java

In everyday Java we do not write ArrayStack or RingQueue ourselves; we use ArrayDeque, which does both. The program below uses it once as a stack and once as a queue on the same three letters, and then runs the bracket checker from the picture.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
public class StackVsQueue {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>(); // used as a stack: push and pop at the front
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.peek()); // C (the last one in)
System.out.println(stack.pop()); // C
System.out.println(stack.pop()); // B
Queue<String> queue = new ArrayDeque<>(); // used as a queue: offer at the back, poll at the front
queue.offer("A");
queue.offer("B");
queue.offer("C");
System.out.println(queue.peek()); // A (the first one in)
System.out.println(queue.poll()); // A
System.out.println(queue.poll()); // B
System.out.println(isBalanced("{[()]}")); // true (a stack matches the latest opener)
System.out.println(isBalanced("([)]")); // false
}
// A typical stack job: every closing bracket must match the most recent unmatched opener.
static boolean isBalanced(String s) {
Deque<Character> open = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
switch (ch) {
case '(', '[', '{' -> open.push(ch);
case ')' -> { if (open.isEmpty() || open.pop() != '(') return false; }
case ']' -> { if (open.isEmpty() || open.pop() != '[') return false; }
case '}' -> { if (open.isEmpty() || open.pop() != '{') return false; }
default -> { }
}
}
return open.isEmpty();
}
}

Let us read main in the order it runs. The first ArrayDeque is declared as a Deque and used as a stack. Three pushes put A, B and C on top of each other, peek shows C without removing it, and two pops return C and then B, the newest first.

The second ArrayDeque is declared as a Queue, so only queue methods are in view. Three offers put A, B and C at the back, peek shows A, and two polls return A and then B, the oldest first. The two blocks of output, C C B and A A B, are the whole difference between the structures.

isBalanced is the job from the picture. The switch pushes every opener. At each closer it first checks isEmpty, because a closer with no opener waiting, as in ), is unbalanced, and pop on an empty ArrayDeque would throw an exception. Then it pops and compares. After the loop, open.isEmpty() is the last check, because a string like (( has no wrong closer but leaves openers waiting. So main prints true for {[()]} and false for ([)].

Two cautions are worth knowing. java.util.Stack still exists, but it is an old class built on the synchronized Vector, slower and able to read any index, so modern code prefers ArrayDeque. And ArrayDeque refuses null items, because poll and peek return null to say the deque is empty.

8Follow-up questions

What is a deque, and how does it relate to both?

A deque, short for double ended queue and said like deck, lets us add and remove at both ends. If we only ever add and remove at the same end, it behaves as a stack. If we add at one end and remove at the other, it behaves as a queue. Java's Deque interface offers both sets of methods, push and pop at the front, offer and poll at the back and front, and ArrayDeque implements it with the same circular buffer we drew, which is why one class can replace both Stack and a linked list used as a queue.

Is a priority queue a kind of queue?

Only in name. A priority queue removes the item with the highest priority, which in Java means the smallest by natural order or by a comparator, not the oldest item. It is usually built as a binary heap, a tree stored in an array, so offer and poll cost O(log n) instead of O(1). It implements Java's Queue interface, but it does not keep first in, first out order, which surprises many people when they print it or iterate over it.

Can you build a queue from two stacks?

Yes. Keep an in stack for offers and an out stack for polls. To offer, push onto the in stack. To poll, if the out stack is empty, pop every item from the in stack and push it onto the out stack, which reverses their order so the oldest is on top, and then pop from the out stack. Each item is moved at most once, so although one poll can be slow, the average cost per operation stays O(1).

9Conclusion

A stack and a queue both store items in arrival order and add and remove in O(1) time. The difference is one rule. A stack, like a pile of plates, removes the newest item first, last in, first out, and inside it is an array with a size counter. A queue, like a line at a counter, removes the oldest first, first in, first out, and inside it is a ring of slots with head and tail markers that wrap round. When a problem needs the most recent unfinished item first, such as matching brackets, undo or depth first search, use a stack; when arrival order or levels matter, such as scheduling or breadth first search, use a queue. In Java, ArrayDeque serves as both.

What to say in the interviewAbout 90 seconds aloud

Open with

Both a stack and a queue hold items in the order they were added; the difference is which item comes out next. A stack is last in, first out, like a pile of plates: push and pop happen at the same end, so the newest item comes out first.

Then, if they want more

A queue is first in, first out, like a line at a counter: we add at the back and remove from the front, so the oldest comes out first. Both give O(1) add and remove and a peek.

Inside, a stack is an array with a size counter that is also the next free slot, or a linked list used at its head. A queue on an array is a circular buffer, with head and tail indexes that wrap round, so removing from the front shifts nothing.

I pick a stack when the most recent unfinished item must be handled first, such as matching brackets, undo, the call stack or depth first search. I pick a queue when arrival order matters, such as scheduling jobs or breadth first search, which finds shortest paths in unweighted graphs.

In Java I use ArrayDeque for both, rather than the old synchronized Stack class. And a priority queue is different from both, since it removes by priority in O(log n).

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 53 times in that collection. How it is counted
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 "How does a stack differ from a queue?": https://scrivio-interview-library.netlify.app/data-structures/solutions/how-does-a-stack-differ-from-a-queue-11c559/