What is Stack Implementation Using Array?
A stack follows LIFO (Last In, First Out), meaning whatever you pushed most recently is the first thing that comes back out. Backing it with an array is the most direct way to build one, since push and pop just work on the array's last index in constant time.
Initialize
An empty array is allocated with a fixed capacity, and the top pointer starts at -1 to signal there's nothing on the stack yet.
push()
If the array isn't already at capacity, the top pointer is incremented first, then the new value is written at that index, so top always marks the most recently added element.
↓ push(7) ↓
pop()
The element at array[top] is read and returned, then the top pointer is decremented; the value itself is left in the array, just no longer considered part of the stack.
↓ pop() → returns 7 ↓
peek()
Returns array[top] without touching the pointer, so the stack is left exactly as it was, useful for checking what's on top before deciding whether to pop.
isEmpty() & isFull()
Both are just pointer comparisons: isEmpty() is true when top equals -1, and isFull() is true when top reaches the array's last valid index.
isEmpty() → true
isFull() → true
Time Complexity
| Operation | Complexity |
|---|---|
| push() | O(1) |
| pop() | O(1) |
| peek() | O(1) |
| isEmpty() | O(1) |
Key Characteristics
- LIFO Principle: Last element added is first removed
- Dynamic Size: Can grow until memory limits
- Efficiency: All operations work in constant time
- Versatility: Foundation for many algorithms