Array-based stack
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
An array-based stack keeps its items in a numbered row and remembers one number: the position of the top. Pushing writes into the next slot and moves that number up; popping moves it down. It is very fast and uses memory in one tidy block.
Practical use cases
- Web app: Move history in an online game. A browser chess or puzzle game stores every move in an array and keeps a counter of how many moves were made. Undo just lowers the counter by one, and a new move writes into the next slot. Nothing is copied, so even a long game responds instantly.
- Web app: Multi-step form wizard. A multi-step booking form stores the answers from each step in an array. Going back lowers the top marker and going forward adds a new entry. Because the form never has more than 10 steps, the array can be created once at that fixed size.
- System: Embedded devices and thread stacks. A calculator chip or small device with very little memory reserves a fixed block for its stack and uses a single counter. Programming languages also give each thread a fixed block for its call stack, which is why endless recursion fails with a stack overflow instead of using all memory.
The story: The Shelf with a Finger
Kabir's cricket club had one narrow locker shelf with exactly four slots for helmets. The coach had a rule: new helmets go into the first empty slot, and when someone needs one, they take the latest helmet from the highest filled slot. Nobody digs into the middle.
The scorer, little Aarav, wanted to keep track without counting slots every time. So he pointed a finger at the highest filled slot and moved it along: finger goes up when a helmet is added, finger goes down when one is taken. When the shelf was empty, his finger pointed at "nothing", which he called -1.
One Sunday, five helmets arrived for four slots. "Shelf full!" shouted Aarav, finger stuck at the top slot. Rather than squeeze the fifth in and crush the first, the club refused it politely. In code this is overflow. If someone asked for a helmet from an empty shelf, that is underflow.
That shelf is an array-based stack: a fixed-size array plus one number, top. Push is "move top up, store". Pop is "read, move top down". No items are ever shifted.
How to spot this problem, and where you need it
You need a stack that is fast and predictable in memory, usually with a known upper limit on how many items it will ever hold, and you want to avoid creating many small objects.
Signs you need it
- You know a sensible maximum size ahead of time, such as 10 steps, 100 moves or 1,000 nested levels.
- Memory is limited or you care about speed, so a plain array with a counter is better than many linked objects.
- You are being asked to handle "stack full" and "stack empty" situations explicitly.
Where to use it in a project
- Game state history and undo features in browser or mobile apps.
- Backtracking and search routines that push choices and pop them when stuck.
- Small devices, scripts or interpreters with fixed memory.
The solution
Create an array of a fixed size and a variable called top that starts at minus one (empty). To push, check that the array is not full, increase top, and store the item at that position. To pop, check that it is not empty, read the item at top and decrease top. The array itself never needs to be erased, since stale values get overwritten later.
Payoff: Before: copying or shifting an array on every undo. After: one counter change per push or pop.
Explain it like I am 8
Imagine an egg tray with a few cups in a row. You always fill the next empty cup, and a little arrow marks the last filled one. Take an egg out and the arrow steps back. If every cup is full, the tray says "no more!"
How it works, step by step
- Make an array of a fixed capacity and set
top = -1(means: empty). - push(x): if
topis the last index, report overflow. Otherwise dotop = top + 1and storexatdata[top]. - pop(): if
top = -1, report underflow. Otherwise readdata[top], then dotop = top - 1. - peek(): return
data[top](when not empty). isEmpty:top === -1. - Remember: popped values may still sit in memory, but anything above
topis ignored.
The code in four languages
PHP
<?php
// A stack stored in a fixed-size array. $top points at the newest item.
class ArrayStack {
private array $data;
private int $top = -1; // -1 means empty
public function __construct(private int $capacity) {
$this->data = array_fill(0, $capacity, null);
}
public function push(mixed $x): void {
if ($this->top === $this->capacity - 1) {
throw new OverflowException('Stack overflow: shelf is full');
}
$this->data[++$this->top] = $x; // move top up, then store
}
public function pop(): mixed {
if ($this->top === -1) {
throw new UnderflowException('Stack underflow: nothing to pop');
}
$x = $this->data[$this->top];
$this->data[$this->top--] = null; // clear it, then move top down
return $x;
}
public function peek(): mixed {
if ($this->top === -1) throw new UnderflowException('Stack is empty');
return $this->data[$this->top];
}
}
$s = new ArrayStack(3);
$s->push(10);
$s->push(20);
$s->push(30);
try {
$s->push(40); // the 4th does not fit
} catch (OverflowException $e) {
echo $e->getMessage() . PHP_EOL;
}
echo $s->pop() . ' ' . $s->peek() . PHP_EOL; // 30 20JavaScript
// A stack stored in a fixed-size array. top points at the newest item.
class ArrayStack {
constructor(capacity) {
this.data = new Array(capacity).fill(null);
this.top = -1; // -1 means empty
}
push(x) {
if (this.top === this.data.length - 1) {
throw new Error('Stack overflow: shelf is full');
}
this.data[++this.top] = x; // move top up, then store
}
pop() {
if (this.top === -1) {
throw new Error('Stack underflow: nothing to pop');
}
const x = this.data[this.top];
this.data[this.top--] = null; // clear it, then move top down
return x;
}
peek() {
if (this.top === -1) throw new Error('Stack is empty');
return this.data[this.top];
}
}
const s = new ArrayStack(3);
s.push(10);
s.push(20);
s.push(30);
try {
s.push(40); // the 4th does not fit
} catch (e) {
console.log(e.message);
}
console.log(s.pop(), s.peek()); // 30 20Java
public class Main {
// A stack stored in a fixed-size array. top points at the newest item.
static class ArrayStack {
private final Integer[] data;
private int top = -1; // -1 means empty
ArrayStack(int capacity) {
data = new Integer[capacity];
}
void push(int x) {
if (top == data.length - 1) {
throw new IllegalStateException("Stack overflow: shelf is full");
}
data[++top] = x; // move top up, then store
}
int pop() {
if (top == -1) {
throw new IllegalStateException("Stack underflow: nothing to pop");
}
int x = data[top];
data[top--] = null; // clear it, then move top down
return x;
}
int peek() {
if (top == -1) throw new IllegalStateException("Stack is empty");
return data[top];
}
}
public static void main(String[] args) {
ArrayStack s = new ArrayStack(3);
s.push(10);
s.push(20);
s.push(30);
try {
s.push(40); // the 4th does not fit
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // Stack overflow: shelf is full
}
System.out.println(s.pop() + " " + s.peek()); // 30 20
}
}Go
package main
import (
"errors"
"fmt"
)
// ArrayStack is a stack stored in a fixed-size array. top points at the newest item.
type ArrayStack struct {
data []int
top int // -1 means empty
}
func NewArrayStack(capacity int) *ArrayStack {
return &ArrayStack{data: make([]int, capacity), top: -1}
}
func (s *ArrayStack) Push(x int) error {
if s.top == len(s.data)-1 {
return errors.New("Stack overflow: shelf is full")
}
s.top++ // move top up, then store
s.data[s.top] = x
return nil
}
func (s *ArrayStack) Pop() (int, error) {
if s.top == -1 {
return 0, errors.New("Stack underflow: nothing to pop")
}
x := s.data[s.top]
s.data[s.top] = 0 // clear it, then move top down
s.top--
return x, nil
}
func (s *ArrayStack) Peek() (int, error) {
if s.top == -1 {
return 0, errors.New("Stack is empty")
}
return s.data[s.top], nil
}
func main() {
s := NewArrayStack(3)
s.Push(10)
s.Push(20)
s.Push(30)
if err := s.Push(40); err != nil { // the 4th does not fit
fmt.Println(err) // Stack overflow: shelf is full
}
popped, _ := s.Pop()
top, _ := s.Peek()
fmt.Println(popped, top) // 30 20
}Time: O(1) per operation · Extra space: O(capacity). Only the top number changes, so every operation is instant. The shelf always takes room for its full capacity, used or not.
Watch out for
- Forgetting the overflow check. In languages like C this silently writes outside the array; in PHP and JS arrays just grow, hiding the bug.
- Starting top at 0 for an empty stack. Then slot 0 looks used. Start at -1, or track a separate size.
- Moving top before checking. Check first, then change, or a failed push leaves the stack broken.
Quick check
- In an array-based stack, what does top = -1 mean?
- The stack is empty
- The stack has one item
- The stack is full
- A stack with capacity 4 already holds 4 items. You push again. What is this called?
- Underflow
- Overflow
- Peeking
- Why is pop() quick in an array-based stack?
- It sorts the array first
- It shifts every item left
- It only reads the slot at top and moves top down