Browse Curriculum

The Stack Pattern

A stack holds elements whose fate is still undecided. The monotonic variant keeps its contents in sorted order by popping anything that violates that order as new elements arrive — and each pop is the moment an earlier element gets its answer.

9
Interactive problems
2
Free to open

How to recognise a stack problem

The problem asks for the next greater or smaller element, needs matching pairs validated (brackets, tags), or involves undoing and revisiting recent state. Histogram and temperature problems are monotonic stack in disguise.

Time and space complexity

O(n) time, because every element is pushed once and popped at most once, against O(n²) for scanning forward from each position.

Stack practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.


Related patterns and concepts

The underlying technique is covered from first principles in the stack lesson in the DSA visualizer curriculum. Stack is one of the 16 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.