Browse curriculum

Stack

Stack Interview Questions: 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. Below are the stack interview questions from LeetCode, each with a step-by-step visual solution.

24

Interactive problems

3

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 interview questions: 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)
Monotonic Stack PatternMediumΩ(n)Θ(n)O(n)O(n)
Daily TemperaturesMediumΩ(n)Θ(n)O(n)O(n)
Largest Rectangle in HistogramHardΩ(n)Θ(n)O(n)O(n)
Maximal RectangleHardΩ(rows · cols)Θ(rows · cols)O(rows · cols)O(cols)
Evaluate Reverse Polish NotationMediumΩ(n)Θ(n)O(n)O(n)
Min StackMediumΩ(1)Θ(1)O(1)O(n)
Implement Queue using StacksEasyΩ(1)Θ(1)O(n)O(n)
Car FleetMediumΩ(n log n)Θ(n log n)O(n log n)O(n)
Next Greater Element IEasyΩ(m + n)Θ(m + n)O(m + n)O(n)
Next Greater Element IIMediumΩ(n)Θ(n)O(n)O(n)
Asteroid CollisionMediumΩ(n)Θ(n)O(n)O(n)
Online Stock SpanMediumΩ(1)Θ(1)O(n)O(n)
Sum of Subarray MinimumsMediumΩ(n)Θ(n)O(n)O(n)
Sum of Subarray RangesMediumΩ(n)Θ(n)O(n)O(n)
Remove K DigitsMediumΩ(n)Θ(n)O(n)O(n)
Simplify PathMediumΩ(n)Θ(n)O(n)O(n)
Basic Calculator IIMediumΩ(n)Θ(n)O(n)O(n)
Basic CalculatorHardΩ(n)Θ(n)O(n)O(n)
Removing Stars From a StringMediumΩ(n)Θ(n)O(n)O(n)
Remove All Adjacent Duplicates in StringEasyΩ(n)Θ(n)O(n)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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern