Browse curriculum

Stack

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

Recognise

How do you 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.

Complexity

What is the time complexity of the stack pattern?

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

Problems

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++.

Complexity

Stack problems by difficulty and complexity

The difficulty, running time and extra space of every stack solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Stack OverviewEasyΩ(1)Θ(1)O(1)O(n)
Valid ParenthesesEasyΩ(1)Θ(n)O(n)O(n)
Decode StringMediumΩ(n)Θ(n + L)O(n · L)O(n + L)
Longest Valid ParenthesesHardΩ(n)Θ(n)O(n)O(n)
Overview (Monotonic Stack)MediumΩ(n)Θ(n)O(n)O(n)
Daily TemperaturesMediumΩ(n)Θ(n)O(n)O(n)
Largest Rectangle in HistogramHardΩ(n)Θ(n)O(n)O(n)
Evaluate Reverse Polish NotationMediumΩ(n)Θ(n)O(n)O(n)
Min StackMediumΩ(1)Θ(1)O(1)O(n)
Curriculum

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

Directory

Every other coding interview pattern