Data Structures · Visualization
Implement Stack (Array)
Stack
A stack can be built on top of a plain array by always treating the end of the array as the 'top'. Time: O(1) amortized for push/pop at the end. Space: O(n).
Big-O: push / pop / peek are all O(1).
Implement Stack (Array)
StackA stack can be built on top of a plain array by always treating the end of the array as the 'top'. Adding an item means appending it to the end, and removing an item means taking the last element off — both of which arrays already do efficiently.
How Implement Stack (Array) Works
- Use an array and a variable (or the array's own length) to track the top.
- Push: add the new value to the end of the array.
- Pop: remove and return the value at the end of the array.
- Peek: return the value at the end of the array without removing it.
Implement Stack (Array) Worked Example
Input: Array-backed stack: push(5), push(8), pop()
- push(5) → array: [5]
- push(8) → array: [5, 8]
- pop() → removes last element (8) → array: [5]
Output: Popped: 8, stack now: [5]
Press ▶ Run to watch it step by step.
# Stack: LIFO, array-backed
stack = [1, 2, 3]
stack.append(1) # push
stack.append(2)
top = stack[-1] # peek
stack.pop() # pop
# All operations are O(1)
# example: stack 5 on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Implement Stack (Array) Time & Space Complexity
When to Use Implement Stack (Array)
- The simplest, most common way to implement a stack in most languages
- Function call stacks and expression evaluators
- Any scenario needing LIFO behavior with fast operations
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.