Data Structures · Visualization
Stack: Push
Stack
Pushing adds a new item to the top of the stack. Time: O(1). Space: O(1) per operation.
Big-O: push / pop / peek are all O(1).
Stack: Push
StackPushing adds a new item to the top of the stack. The visualizer's default stack is [1, 2, 3] with 3 on top, and its default push value is 7, so the first frame writes 7 into index 3 and the top moves from index 2 to index 3. Nothing already in the stack moves: an array-backed stack appends into the next free slot, while a linked-list stack rewires a single pointer. That is why push is O(1) worst case whenever capacity is available, and only an occasional O(n) amortised when a dynamic array has to grow.
How Push Works
- Take the new value to add — the visualizer uses 7.
- Check capacity: a fixed-size array implementation reports overflow instead of writing past the end.
- Place it just above the current top, at index length (3 in the default stack).
- Update the 'top' reference (or array length) to point to this new item.
- Leave every existing element untouched — push never shifts or searches.
Push Worked Example
Input: push(7) on the default stack [1, 2, 3]
- Current stack, bottom on the left: [1, 2, 3] — 3 sits on top at index 2.
- 7 is written at index 3, the first free slot: [1, 2, 3, 7].
- The top moves to index 3, so a following peek() returns 7 and pop() removes 7 first.
Output: [1, 2, 3, 7] with 7 on top
Press ▶ Run to watch it step by step.
stack = [1, 2, 3]
stack.append(10) # push on top
stack.append(20)
print(stack) # [10, 20] top = 20
# example: push 7 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.
Push Time & Space Complexity
When to Use Push
- Adding a new function call onto the call stack
- Recording a new action for undo history
- Adding an opening bracket while validating expressions
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.