Implement Stack using Arrays
Build a stack — push, pop, top, size — on a fixed array.
Intuition
A stack is just an array plus one integer: top, the index of the last element. Push writes at top+1; pop reads at top and steps back. Nothing ever moves — that's why every operation is O(1).
The foundational exercise: a stack is an array plus one index. Everything interesting is in the boundary conditions — top == -1 means empty, top == capacity - 1 means full. Getting those two right is the whole problem, and they're the same two checks every fixed-capacity structure needs.
Approach
One pointer does everything
top = -1 means empty. push: top += 1; a[top] = x. pop: read a[top], top -= 1.
Guard the edges
Pop/peek on empty (top == −1) is underflow; push on a full fixed array (top == cap−1) is overflow — check both.
Dynamic variant
Doubling the array on overflow gives amortized O(1) push — that's exactly what Python's list.append does.
Solution & live demo
Common pitfalls
Incrementing the index after writing
self.a[self.top] = x self.top += 1
self.top += 1 self.a[self.top] = x
With top starting at −1 as the empty marker, writing first targets index −1, which in Python silently overwrites the last slot of the array. Advance to the new position, then write to it.
Checking overflow against the wrong bound
if self.top == len(self.a): raise OverflowError
if self.top == len(self.a) - 1: raise OverflowError
top is the index of the last stored item, so a full array has top == capacity - 1. Comparing against capacity lets one extra push run off the end.
Returning a value after decrementing
self.top -= 1 return self.a[self.top]
v = self.a[self.top] self.top -= 1 return v
Decrementing first returns the element below the top — the one that should survive the pop. Read the value while the index still points at it.
Edge cases
Explicit underflow check; raise or return sentinel.
top bounces at the boundary; indices never leak past it.