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

Stack

Pushing 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

  1. Take the new value to add — the visualizer uses 7.
  2. Check capacity: a fixed-size array implementation reports overflow instead of writing past the end.
  3. Place it just above the current top, at index length (3 in the default stack).
  4. Update the 'top' reference (or array length) to point to this new item.
  5. Leave every existing element untouched — push never shifts or searches.

Push Worked Example

Input: push(7) on the default stack [1, 2, 3]

  1. Current stack, bottom on the left: [1, 2, 3] — 3 sits on top at index 2.
  2. 7 is written at index 3, the first free slot: [1, 2, 3, 7].
  3. 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

Try your own input
Stack: PushO(1)
Places a new value on top of the stack.
bottom
1
2
3
← top
Active / highlighted Min stack Result
Stack: Push
Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
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]
Input: push(7) on the default stack [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

TimeO(1)
SpaceO(1) per operation

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.