Stack Using Array

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: top is -1.
  • Push the first item: top becomes 0.
  • Push again: top becomes 1, and so on.
  • The stack is empty whenever top equals -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 top equals capacity - 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 top equals -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.

  1. Make an array of a fixed capacity and set top to -1.
  2. Push: if top is capacity - 1, report overflow. Else increase top by one and store the item at array[top].
  3. Pop: if top is -1, report underflow. Else read array[top], then decrease top by one, and return the read value.
  4. Peek: if top is -1, the stack is empty. Else return array[top] without changing top.
  5. The stack is empty when top is -1, and full when top is capacity - 1.

Here is how top moves as we push three items and then pop one.

top = -1 (empty)

push 10 -> top = 0

push 20 -> top = 1

push 30 -> top = 2

pop -> returns 30, top = 1

πŸ’» 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.

stack_array.py
CAPACITY = 5
stack = [0] * CAPACITY # fixed-size array
top = -1 # empty stack
# push adds a value on top, checks for overflow
def 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 underflow
def 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 it
def 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:

Output
Pushed 10
Pushed 20
Pushed 30
Top item is 30
Popped 30
Popped 20
Top item is now 10

Tip

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 top at 0 instead of -1. Then your empty check and your first push both go wrong.
  • Storing the value before moving top up in push. The order matters: move top first, 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 top down 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. 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. 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. 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. 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.

πŸš€ What’s Next?

Share & Connect