Stack Using Array
Table of Contents + β
You already know what a stack does. It takes items, stores them, and gives back the last one you put in. Now comes the real question. How do you actually build one? The good news is you do not need anything fancy. A plain array and one small number is enough. In this tutorial we build a stack from scratch using just that.
π₯ The Real-World Picture
Think about a stack of plates in your kitchen. You wash a plate and place it on top. You wash another and place it on top again. When you need a plate, you grab the top one. You never pull one out from the middle. That top plate is the last one you put down. And it is the first one you take.
Now picture the same plates sitting in a row on a long shelf with fixed slots. The shelf is our array. An array is a fixed line of boxes sitting next to each other in memory. We just need to remember which slot holds the topmost plate. That is the whole trick.
π― What We Are Building
We will build a stack that lives inside an array of a fixed size. So it can hold only so many items, no more. We track everything with one helper number.
- An array to actually store the items.
- A capacity, which is the most items the array can hold.
- A top index, which points to the slot of the item currently on top.
The star here is top. It is just a number that says βthe topmost item is sitting at this index.β Every push and pop is really just moving this one number up or down.
π’ Why top Starts at -1
When the stack is empty, there is no top item at all. So what number do we give top? We cannot point it at slot 0. Slot 0 is a real slot where the first item will go. If top already said 0 on an empty stack, the code would think slot 0 holds something. That would be a lie.
So we start top at -1. That means the stack is empty. Array indexes start at 0, so -1 is one step before the first real slot. It is a clean way to say there is nothing here yet.
- Empty stack:
topis-1. - Push the first item:
topbecomes0. - Push again:
topbecomes1, and so on. - The stack is empty whenever
topequals-1.
β¬οΈ Push: Add an Item on Top
Push means put a new item on top of the stack. The order matters here. First we move top up by one. Then we store the new item at that fresh slot.
But wait. What if the array is already full? You cannot place a plate when there is no empty shelf left. That full situation is called overflow. It means the stack has no room for one more item. We must check for it before we add anything.
Here is the simple logic for push.
- If
topequalscapacity - 1, the stack is full. Report overflow and stop. - Otherwise, do
top = top + 1. - Then store the new item at
array[top].
β¬οΈ Pop: Remove the Top Item
Pop means take the top item off and give it back. This is push in reverse. First we read the item sitting at top. Then we move top down by one.
And again there is a danger. What if the stack is already empty? You cannot grab a plate from an empty shelf. That empty situation is called underflow. It means you tried to remove from a stack that has nothing in it. So we check for it first.
Here is the logic for pop.
- If
topequals-1, the stack is empty. Report underflow and stop. - Otherwise, read the value at
array[top]so we can return it. - Then do
top = top - 1.
Note
Notice we do not erase the old value from the array. We just move top down. The old number is still sitting in memory, but the stack ignores it. The next push will write over that slot anyway. So there is no need to clean it.
π Peek: Look Without Removing
Sometimes you just want to see the top item without taking it off. That is peek. It reads array[top] and returns it, but it does not touch top at all. If the stack is empty, there is nothing to peek, so we report that too.
π Steps to Build the Stack
Let us put it all together. Here is the full plan before we write code.
- Make an array of a fixed
capacityand settopto-1. - Push: if
topiscapacity - 1, report overflow. Else increasetopby one and store the item atarray[top]. - Pop: if
topis-1, report underflow. Else readarray[top], then decreasetopby one, and return the read value. - Peek: if
topis-1, the stack is empty. Else returnarray[top]without changingtop. - The stack is empty when
topis-1, and full whentopiscapacity - 1.
Here is how top moves as we push three items and then pop one.
π» The Code in 5 Languages
Now we write a fixed-capacity array stack. It has push, pop, and peek. Then a small demo pushes a few numbers, peeks, pops, and prints what happens. Watch how top drives all of it.
CAPACITY = 5stack = [0] * CAPACITY # fixed-size arraytop = -1 # empty stack
# push adds a value on top, checks for overflowdef push(value): global top if top == CAPACITY - 1: print(f"Overflow! Cannot push {value}") return top = top + 1 # move top up first stack[top] = value # then store the value print(f"Pushed {value}")
# pop removes and returns the top value, checks for underflowdef pop(): global top if top == -1: print("Underflow! Stack is empty") return -1 value = stack[top] # read the top top = top - 1 # then move top down return value
# peek returns the top value without removing itdef peek(): if top == -1: print("Stack is empty") return -1 return stack[top]
push(10)push(20)push(30)print(f"Top item is {peek()}")print(f"Popped {pop()}")print(f"Popped {pop()}")print(f"Top item is now {peek()}")The output of the above code will be:
Pushed 10Pushed 20Pushed 30Top item is 30Popped 30Popped 20Top item is now 10Tip
Every single operation here is O(1), which means constant time. Push, pop, and peek all touch just one slot and change one number. They never loop over the whole array. So it does not matter if the stack holds five items or five thousand. Each operation takes the same small amount of time.
β±οΈ Time and Space Complexity
Here is the cost of each operation. Notice how everything runs in O(1) time.
| Operation | Time | Why |
|---|---|---|
| Push | O(1) | Moves top up and writes one slot |
| Pop | O(1) | Reads one slot and moves top down |
| Peek | O(1) | Reads one slot, changes nothing |
| Space | O(n) | The array holds up to n items |
Caution
The big catch with an array stack is the fixed size. You pick the capacity up front, and you cannot go past it. If you try, you hit overflow. So you either guess a size big enough, or you switch to a stack built on a linked list, which can grow as needed. We cover that one next.
β οΈ Common Mistakes
A few traps catch beginners every time. Watch out for these.
- Starting
topat0instead of-1. Then your empty check and your first push both go wrong. - Storing the value before moving
topup in push. The order matters: movetopfirst, then store. - Forgetting the overflow check, so a push writes past the end of the array and crashes the program.
- Forgetting the underflow check, so a pop on an empty stack reads garbage or crashes.
- Erasing slots after a pop. You do not need to. Just moving
topdown is enough.
π§© What Youβve Learned
β
A stack can be built from just an array plus one top index.
β
top starts at -1 to mean the stack is empty.
β
Push moves top up first, then stores the value, after checking for overflow.
β
Pop reads the top value, then moves top down, after checking for underflow.
β
Peek reads the top value without changing top.
β Push, pop, and peek all run in O(1) constant time.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why does top start at -1 in an array-based stack?
Why: Index 0 is a real slot where the first item goes, so -1 cleanly means 'nothing here yet'.
- 2
What is the correct order of steps inside push?
Why: Push moves top up to a fresh slot first, then writes the new value into that slot.
- 3
What is it called when you try to push onto a full array stack?
Why: Overflow happens when top is already at capacity - 1 and there is no room for one more item.
- 4
What is the time complexity of push, pop, and peek in this array stack?
Why: Each operation touches one slot and changes one number, so it runs in constant O(1) time.