Monotonic Stack
monotonic-stack
Algorithms
Advanced Greedy & Data Structures
"For each element in the array, find the next greater element" is a brute-force `O(n^2)` problem until you notice that a stack maintained in decreasing order lets you answer every query as a side effect of a single left-to-right scan. The whole algorithm runs in `O(n)`, and the same monotonic-stack pattern solves trapping rain water, largest rectangle in a histogram, stock spans, and a long tail of related problems with the same template. **Advanced Greedy & Data Structures** is where greedy thinking meets specialized scaffolding. You will implement the monotonic stack pattern for next-greater and next-smaller variants, the monotonic deque for sliding-window maximum and minimum (also a key DP optimization), and sweep-line algorithms for interval and event problems (meeting rooms, interval merge, rectangle area union). The lesson closes with advanced greedy problems that need a heap or priority queue: full Huffman encoding, task scheduling with cooldown, the gas station problem, and activity selection with deadlines and profits. In **Greedy (Intro)**, you saw simple greedy strategies that needed only sorting. **Heaps & Priority Queue** taught you `O(log n)` access to the minimum or maximum, which is exactly what these advanced greedy patterns rely on for their efficiency. Next, **Branch and Bound** extends backtracking with the same kind of bounding-function pruning, applied to optimization search trees.
Not Started
0%
Practice Problems
Next Greater Element I
Given two arrays where nums1 is a subset of nums2, find the next greater element in nums2 for each element in nums1.
Largest Rectangle in Histogram
Given an array of bar heights representing a histogram, find the area of the largest rectangle that can be formed within the histogram.
Maximal Rectangle
Given a 2D binary matrix filled with '0's and '1's, find the area of the largest rectangle containing only '1's.
Trapping Rain Water
Given an elevation map, compute how much water it can trap after raining.
Car Fleet
Given positions and speeds of cars heading toward a target, determine how many car fleets will arrive at the destination.
Daily Temperatures
Given an array of daily temperatures, return how many days you have to wait for a warmer temperature for each day.
Sum of Subarray Minimums
Given an array of integers, find the sum of the minimum value of every contiguous subarray, modulo 10^9 + 7.
Community
Online Stock Span
Design an online structure that returns the streak of consecutive previous days with price <= today, using a monotonic stack of (price, span) pairs.
Monotonic Stack: The Pattern Everyone Skips
The next-greater-element trick that turns O(n^2) scans into O(n). Daily temperatures, largest rectangle in histogram, and trapping rain water, all from the same shape.
