Py

Stacks & Monotonic Stacks

Unit 6 of 15
📚

Core Patterns

Stacks & Monotonic Stacks

Last in, first out: match brackets, evaluate expressions, carry extra state, and use monotonic stacks to find the next greater or smaller element in O(n).

0 of 3 lessons complete, 0 of 7 problems solved

Start unitPattern cheatsheet

Coursework

35 min

1
Up next

Stacks: Last In, First Out

Use a Python list as a stack and spot the nesting problems it solves.

10 min
2

Stacks That Carry State

Push pairs to remember a running minimum, and evaluate expressions with a stack.

11 min
3

Monotonic Stacks: Next Greater Element

Answer 'next greater / smaller' for every element in one O(n) pass.

14 min

Practice ladder

Start with the first problem, then work toward the harder variations. Run examples before submitting against all tests.

1.Valid Parentheses

Check that every bracket is closed by the right type, in the right order.

EasyLC #20
2.Next Greater Element I

Look up each query's next greater element in another array.

EasyLC #496
3.Min Stack

Design a stack that also returns its minimum in O(1).

MediumLC #155
4.Evaluate Reverse Polish Notation

Compute the value of a postfix arithmetic expression.

MediumLC #150
5.Daily Temperatures

For each day, count the days until a warmer one.

MediumLC #739
6.Car Fleet

Count the groups of cars that reach the destination together.

MediumLC #853
7.Largest Rectangle in Histogram

Find the biggest rectangle that fits under a bar chart.

HardLC #84
Next unit: Binary Search