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)

Stack

A 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

  1. Use an array and a variable (or the array's own length) to track the top.
  2. Push: add the new value to the end of the array.
  3. Pop: remove and return the value at the end of the array.
  4. 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()

  1. push(5) → array: [5]
  2. push(8) → array: [5, 8]
  3. pop() → removes last element (8) → array: [5]

Output: Popped: 8, stack now: [5]

Try your own input
bottom
1
2
3
← top
Active / highlighted Min stack Result

Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
# 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]
Input: Array-backed stack: push(5), push(8), pop()

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

TimeO(1) amortized for push/pop at the end
SpaceO(n)

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

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.