Quick revision
The short answer
A stack is a collection that lets us add and remove elements at one end only, the top, so the last element added is the first one removed. It supports push, pop, peek, isEmpty and size, each in O(1) time, and is usually built on an array that doubles when full or on a chain of linked nodes.
The solution
What it costs
| Aspect | Stack | Queue |
|---|---|---|
| Order | last in, first out | first in, first out |
| Add and remove | push and pop at the top | offer at the back, poll at the front |
| Everyday picture | pile of plates, undo list | line at a counter, print jobs |
| Search it drives | depth-first search | breadth-first search |
| Usual Java choice | ArrayDeque: push, pop, peek | ArrayDeque: offer, poll, peek |
What to remember
A stack is a pile of plates in code: elements are added and removed only at the top, so the last one in is the first one out. It supports push, pop, peek, isEmpty and size, each O(1), using either an array with a size counter that doubles when full or a chain of nodes with a top reference. The clue to remember is nesting or anything most recent: when the latest unfinished item must be handled first, reach for a stack.
1What a stack is, starting from a pile of plates
Think of a pile of clean plates in a canteen. A washed plate is always placed on top of the pile, and anyone who needs a plate takes the top one. Nobody pulls a plate out of the middle, because the pile would topple. This pile is the whole idea of a stack. A stack is a collection of elements in which we may add or remove only at one end, and that end is called the top.
Because only the top is reachable, the plate placed last is the first to be taken. Computer scientists call this rule last in, first out, often shortened to LIFO. Let us see it with numbers. Put 1 on the stack, then 2, then 3. Now take elements off one at a time. The first one we can reach is 3, then 2, then 1. The order has come back reversed.
The stack is drawn on its side: the bottom is on the left and the top is on the right.
- pushed
- 1, 2, 3
- popped
- 3, 2, 1
1We pushed 1, then 2, then 3. Only the top, 3, can be taken, so three pops give 3, 2, 1, the reverse of the order they arrived.
If data structures make you uneasy, the stack is a good place to begin, because it is deliberately small. It offers fewer operations than an array or a list, not more, and every one of them touches only the top. You never have to search, shift or count positions. Once you are comfortable with the pile of plates, you already understand almost everything about it.
That reversal is not a side effect; it is the reason stacks exist. A stack remembers things in exactly the order we need to come back to them: the most recent unfinished thing first. An editor's undo list works like this, since the last change you made is the first one undone. So does the back button in a browser, and so does Java itself when one method calls another and must return to the caller afterwards.
Your turn
Solve it before you read on. Above is one example with the result expected for it. If the question leaves something open, such as an empty input or repeated values, note what you would ask the interviewer. 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.
2The five operations, one at a time
Let us meet the operations slowly, one per paragraph, using the pile of plates. The first is push. push(x) places the element x on top of the stack. Nothing else in the stack moves. After push(4) on our stack of 1, 2 and 3, the top is 4.
The second is pop. pop() removes the top element and gives it back to us. After pop() on 1, 2, 3, 4 we receive 4, and the top is 3 again. What should pop do on an empty stack? There is nothing to give back, so it is an error, and in Java it throws an exception.
The third is peek, sometimes called top. peek() tells us what the top element is without removing it, like glancing at the top plate without lifting it. Calling peek twice in a row gives the same answer both times.
The last two are questions about the stack as a whole. isEmpty() answers whether the stack holds any element at all, and size() tells us how many it holds. We usually ask isEmpty before calling pop, so that we never pop from an empty stack by accident.
| Operation | What it does | Time | On an empty stack |
|---|---|---|---|
push(x) | puts x on top | O(1), amortised for an array | works |
pop() | removes and returns the top | O(1) | throws an exception |
peek() | returns the top, leaves it in place | O(1) | throws (or null in some APIs) |
isEmpty() | is there any element? | O(1) | true |
size() | how many elements | O(1) | 0 |
Why does every one of these take the same small amount of time, however large the stack is? Because each one looks only at the top, and the stack always knows where its top is. Doing a fixed amount of work regardless of size is written O(1), read as constant time. The one small exception is push on an array-based stack, which is O(1) on average, as the next section shows.
Notice what is missing from the table. There is no operation to read the fifth element, and no search. If a problem needs to find something in the middle, we would have to pop down to it, which takes time in proportion to the size, O(n). That is a sign that a stack is the wrong tool for that problem.
3How a stack works inside an array
Now let us open the stack and look inside. The most common way to build one is an array plus a counter called size. The elements sit in slots 0 to size - 1, with the bottom in slot 0 and the top in slot size - 1. The counter does two jobs at once: it says how many elements there are, and it is also the index of the next free slot.
So push(x) writes x into slot size and then adds one to size. pop() subtracts one from size and returns the value in that slot. peek() reads slot size - 1. Each is one or two simple steps. The picture runs these steps on an array of four slots, so you can watch size and the top move.
The array is drawn left to right, index 0 first. top marks the last filled slot and size marks the next free one. Dimmed values are old copies the stack no longer counts.
- array length
- 4
- size
- 0
- operation
- new ArrayStack()
1A new stack is an array of 4 empty slots and a counter size = 0. size is also the index of the next free slot.
- array length
- 4
- size
- 1
- operation
- push(1)
2
push(1)writes 1 into slot size, which is 0, and adds one to size. Slot 0 is now the top.- array length
- 4
- size
- 2
- operation
- push(2)
3
push(2)writes into slot 1 and size becomes 2. Nothing else moves; only the top end changes.- array length
- 4
- size
- 3
- operation
- push(3)
4
push(3)writes into slot 2. Each push is one write and one addition, whatever the stack holds.- array length
- 4
- size
- 4
- operation
- push(4)
5
push(4)fills slot 3. size is now 4, equal to the array length, so the array is full.- array length
- 8
- size
- 4
- operation
- push(5), growing
- copied
- 4 values
6
push(5)finds no free slot, so it first copies the four values into a new array twice as long, with 8 slots.- array length
- 8
- size
- 5
- operation
- push(5)
7Now there is room, so 5 goes into slot 4 and size becomes 5. The next three pushes will not need a copy.
- array length
- 8
- size
- 4
- operation
- pop()
- returns
- 5
8
pop()takes one from size and returns items[4], which is 5. The 5 is still in the slot, but the stack no longer counts it.- array length
- 8
- size
- 4
- operation
- peek()
- returns
- 4
9
peek()reads items[size - 1], which is 4, and changes nothing. The top is still slot 3.- array length
- 8
- size
- 5
- operation
- push(9)
10
push(9)writes into slot 4, the next free slot, over the old 5. A popped value is never erased; it is simply overwritten later.
Two moments in the picture deserve a second look. The first is the sixth frame. The array was full, so push(5) had nowhere to write. The stack made a new array twice as long, copied the four values across, and only then wrote 5. That copy costs time in proportion to the number of elements, so one push was slow. But because the array doubles, the next copy happens only after as many cheap pushes as there were elements. Averaged over all the pushes, each costs O(1), which is called amortised O(1).
The second moment is the pop. A beginner often asks whether pop erases the value. It does not. In the eighth frame the 5 is still sitting in slot 4, dimmed, because size now says the stack has only four elements and nothing reads beyond it. In the last frame push(9) simply writes over it. Moving one counter is all a pop needs, which is why it is so fast.
One more detail makes the picture honest. The empty boxes are slots the stack has never used. In Java, a new int array is filled with zeros, so those slots really hold 0, but the stack never reads a slot at or beyond size, so their contents never matter.
4The other way to build it, a chain of nodes
The second way to build a stack uses linked nodes. Each node is a small object holding one value and a reference, a link, to the node below it. The stack itself keeps a single reference, top, to the first node. Think of a chain of paper clips hanging from a hook: you can only add or remove the clip nearest the hook.
push(x) creates a new node whose link is the current top, then makes top refer to the new node. pop() remembers the top node's value, moves top down to the node below, and returns the value. Here is that code, and the picture after it follows push(3) and pop() on a stack holding 2 and 1.
Each box is a node: a value and a link to the node below it. The stack keeps one reference, top, to the first node.
- stack
- top -> 2 -> 1
1After
push(1)andpush(2), top refers to node 2, whose link leads to node 1, whose link is null.- stack
- top -> 3 -> 2 -> 1
2
push(3)makes a new node holding 3 whose link is the old top, node 2, and then moves top onto it. No other node changes.- stack
- top -> 2 -> 1
- returns
- 3
3
pop()saves 3, then moves top down to node 2. Node 3 is left behind, and Java's garbage collector will reclaim it.
| Question | Array and counter | Chain of nodes |
|---|---|---|
| Where is the top? | slot size - 1 | the node that top refers to |
| Cost of push | O(1) amortised, a rare O(n) copy | O(1) always, plus one new object |
| Memory per element | one slot | one node object and a reference |
| Speed in practice | usually faster, slots side by side | slower, nodes scattered |
Why would we choose one over the other? The linked version never needs to copy, so every push is O(1) even in the worst case. But each element costs an extra object and a reference, and the nodes are scattered in memory, which the processor reads more slowly than a row of neighbouring slots. In practice the array version is usually faster, which is why Java's ArrayDeque, the stack most Java code uses, is built on an array.
5A stack beside its close relative, the queue
The stack's nearest relative is the queue, which you know from any line at a ticket counter. People join at the back and are served at the front, so the first to arrive is the first to leave, first in, first out. The two structures differ only in which end we remove from, yet that one difference changes everything built on them.
| Aspect | Stack | Queue |
|---|---|---|
| Order | last in, first out | first in, first out |
| Add and remove | push and pop at the top | offer at the back, poll at the front |
| Everyday picture | pile of plates, undo list | line at a counter, print jobs |
| Search it drives | depth-first search | breadth-first search |
| Usual Java choice | ArrayDeque: push, pop, peek | ArrayDeque: offer, poll, peek |
The clearest example is searching a maze or a graph. With a stack, depth-first search follows one path as deep as it goes before backing up to try another, because the most recently found path is always on top. With a queue, breadth-first search spreads out evenly, one step from the start, then two steps, and so on. Same pieces, opposite ends, very different journeys.
6A stack in Java
The class below builds an int stack on an array that doubles when full, exactly as in the picture, and then shows ArrayDeque used as a stack of characters, which is what we would write in everyday code.
Let us read ArrayStack in the order a program would use it. The array starts with 4 slots and size starts at 0. push first checks whether size equals the array length. If it does, Arrays.copyOf makes an array twice as long holding the same values. Then items[size++] = x writes into the free slot and moves size on, in one line.
pop checks for an empty stack first and throws NoSuchElementException with a clear message, rather than returning a made-up value that would hide the bug. Then items[--size] moves size back first and reads the slot it now points at, which is the top. peek reads items[size - 1] without changing size. So main prints 5, then 4, then 4.
The second half uses ArrayDeque, Java's recommended stack. Its push, pop and peek all work at the same end, so after pushing an open bracket and then a square bracket, pop returns the square bracket and peek shows the round one. The common mistake is to mix in offer or add, which put elements at the other end and quietly break the order. Use push, pop and peek only.
You may also meet the class java.util.Stack. It still works, but it is an old design: it extends Vector, locks itself on every call, and lets callers insert or read at any index, which breaks the rule that only the top is reachable. Its own documentation recommends a Deque instead.
7How to recognise problems that need a stack
Knowing when to reach for a stack matters more in interviews than knowing how to build one. The strongest clue is nesting, things that must close in the reverse order they opened. Take the text ([]). We read the open round bracket and push it, then the open square bracket and push it. When the closing square bracket arrives, it must match the top, which is the square one, so we pop it. The closing round bracket then matches the new top. The stack is empty at the end, so the brackets are balanced.
A second clue is the phrase most recent, or anything that must be undone in reverse. Undo lists, the back button, and evaluating an expression written as 3 4 + 2 *, where each operator applies to the two most recent numbers, all keep their work on a stack.
A third clue is a question about the nearest greater or smaller element to the left or right, such as the next warmer day in a list of temperatures. These use a monotonic stack, a stack whose values only ever increase from bottom to top, or only decrease. We pop every element that can never be an answer again, and each element is pushed and popped at most once, so the whole scan is O(n) instead of the O(n^2) of two loops.
A fourth clue is recursion. Every recursive method already uses a stack, the call stack, to remember where to return. When recursion might go too deep, for instance a depth-first search over a long chain of a million nodes, we can rewrite it with our own ArrayDeque and push the work we still have to do. And whenever a problem simply asks to reverse something, pushing everything and popping it back is the plainest correct answer.
8Follow-up questions
What is the call stack, and what is a StackOverflowError?
When a method is called, Java pushes a frame onto the thread's call stack. The frame holds the method's parameters, its local variables and the place to return to. When the method returns, its frame is popped, so the most recent call always finishes first, last in, first out. The call stack has a fixed size, often around 1 MB per thread on a 64-bit JVM, so very deep recursion runs out of room and Java throws StackOverflowError. Rewriting the recursion with an explicit ArrayDeque moves that bookkeeping to the heap, which is far larger.
How would you design a stack that also returns its minimum in O(1)?
Keep a second stack beside the main one, holding minimums. On every push, also push onto the second stack the smaller of the new value and the current minimum. On every pop, pop both stacks. The top of the second stack is then always the minimum of the elements still in the main stack, because each entry records what the minimum was at the moment that level was pushed. For pushes of 5, 3 and 7 the second stack holds 5, 3, 3, and after one pop the minimum is still 3.
Why is pop on an empty stack an error rather than returning null?
Because popping from an empty stack almost always means a bug, such as a closing bracket with no opening partner. An exception stops the program right at the bug, while a null travels on and causes a failure somewhere far away, which is much harder to trace. Java's Deque offers both styles: pop throws NoSuchElementException, while pollFirst and peekFirst return null. We choose by asking whether an empty stack is a normal situation for our algorithm.
9Conclusion
A stack is a pile of plates in code: elements are added and removed only at the top, so the last one in is the first one out. It supports push, pop, peek, isEmpty and size, each O(1), using either an array with a size counter that doubles when full or a chain of nodes with a top reference. The clue to remember is nesting or anything most recent: when the latest unfinished item must be handled first, reach for a stack.
Open with
A stack is a collection where we add and remove only at one end, the top, so the last element pushed is the first popped, last in, first out.
Then, if they want more
Its operations are push to add on top, pop to remove and return the top, peek to read the top without removing it, and isEmpty and size. All of them are O(1) because they only touch the top. Pop and peek on an empty stack should throw, because that almost always signals a bug.
Inside, I would usually build it on an array with a size counter: push writes at index size and increments it, pop decrements size and returns that slot. When the array is full I double it, so push is amortised O(1).
The alternative is a linked list where each node points to the one below and the stack keeps a top reference; every push is strictly O(1), but each element costs a node object. In Java I would use ArrayDeque with push, pop and peek, not the old java.util.Stack class.
Stacks fit problems with nesting, such as matching brackets, anything most recent first such as undo, nearest greater element problems with a monotonic stack, and replacing deep recursion in depth-first search.
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), Arrays (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 "What is a stack, and which operations does it support?": https://scrivio-interview-library.netlify.app/data-structures/solutions/what-is-a-stack-and-which-operations-does-it-support-a87ea8/