Visual DSA Lab
Lesson 02Foundation 10 minutes

Stacks

Use Last In, First Out ordering when only the most recently added value should be removed.

After this lesson
  • Apply the LIFO rule
  • Trace push, pop, and peek
  • Spot problems that need a stack

Mental model

Values enter and leave from one end called the top. Push adds to the top; pop removes from the top.

Everyday analogy

A stack of plates: you add and remove the plate at the top.

Learn by doing

Interactive visualization

Try multiple operations. Read the trace after every action and connect the visible movement to the operation's complexity.

Interactive data structure

Change the structure and watch the operation

Try an operation and connect the visible movement to its runtime cost.

top
12
28
43
readyOnly the top of the stack is available.

Reasoning checkpoint

Pause and explain the trace

Try to answer each prompt before revealing the explanation.

01RepresentationHow does the physical representation explain the operations you saw?

Values enter and leave from one end called the top. Push adds to the top; pop removes from the top.

02CostWhy can “Push” become O(1)*?

A dynamic-array implementation may occasionally resize.

03CorrectnessWhich implementation mistake should you test explicitly?

Popping an empty stack

Cost model

Operation complexity

OperationAverageWorstWhy
PushO(1)O(1)*A dynamic-array implementation may occasionally resize.
PopO(1)O(1)Only the top item is removed.
PeekO(1)O(1)Reads the top without removing it.
SearchO(n)O(n)A stack is not designed for arbitrary lookup.

* Amortized: occasional expensive work is spread across many cheap operations.

From picture to program

Java implementation

stacks.java
Java
Deque<Integer> stack = new ArrayDeque<>();

stack.push(10);
stack.push(20);

int top = stack.peek(); // 20
int removed = stack.pop(); // 20
ArrayDeque is the usual stack implementation in Java.
Use push, pop, and peek to communicate stack intent.
The call stack is why deeply recursive code can overflow.

Where it appears

  • Function calls and recursion
  • Undo operations and browser navigation
  • Expression parsing, DFS, and backtracking

Common mistakes

  • Popping an empty stack
  • Using Stack in modern Java instead of the Deque interface
  • Trying to access elements in the middle
Coding Shuttle Practice•Concept Check

Which item leaves a stack first?