Many array problems ask, for every element, “where is the next bigger one?” or “how far back do the smaller ones go?”. Checking every pair takes O(n2) time. A monotonic stack answers all of them in a single pass, O(n), by keeping a stack whose values are always in increasing or decreasing order. Each element is pushed once and popped once. This lesson solves three classic problems with it: next greater element, stock span, and the largest rectangle in a histogram.
In this lesson you will learn
- What makes a stack “monotonic”
- The next greater element problem in O(n)
- The stock span problem
- The largest rectangle in a histogram
- Why each element is pushed and popped at most once
You should know the stack data structure and arrays in C.
Next Greater Element and Stock Span
#include <stdio.h>
/* Next greater element with a monotonic (decreasing) stack: O(n) */
static void next_greater(const int *a, int n, int *res) {
int stack[64], top = -1; /* holds indexes whose answer is unknown */
for (int i = 0; i < n; i++) {
while (top >= 0 && a[stack[top]] < a[i])
res[stack[top--]] = a[i]; /* a[i] is the answer for everything smaller below it */
stack[++top] = i;
}
while (top >= 0) res[stack[top--]] = -1; /* no greater element to the right */
}
/* Stock span: days in a row (ending today) with price <= today's price */
static void stock_span(const int *p, int n, int *span) {
int stack[64], top = -1;
for (int i = 0; i < n; i++) {
while (top >= 0 && p[stack[top]] <= p[i]) top--;
span[i] = top < 0 ? i + 1 : i - stack[top];
stack[++top] = i;
}
}
int main(void) {
int a[] = {4, 5, 2, 25, 7, 8, 1};
int n = sizeof a / sizeof a[0], res[64];
next_greater(a, n, res);
for (int i = 0; i < n; i++) printf("%2d -> %2d\n", a[i], res[i]);
int price[] = {100, 80, 60, 70, 60, 75, 85};
int span[64];
stock_span(price, 7, span);
printf("\nprice:");
for (int i = 0; i < 7; i++) printf("%4d", price[i]);
printf("\nspan: ");
for (int i = 0; i < 7; i++) printf("%4d", span[i]);
printf("\n");
return 0;
}
Output
4 -> 5
5 -> 25
2 -> 25
25 -> -1
7 -> 8
8 -> -1
1 -> -1
price: 100 80 60 70 60 75 85
span: 1 1 1 2 1 4 6
- The stack holds indexes of elements still waiting for their answer. Their values decrease from bottom to top, so the stack is monotonic.
- When a new value
a[i]arrives, every waiting element smaller than it has found its next greater element. They are popped and given the answera[i]. For example, 25 answers both 2 and 5. - Elements still on the stack at the end have nothing bigger to their right, so they get -1.
- Each index is pushed once and popped at most once, so the inner
whileloop runs at most n times in total. That makes the whole algorithm O(n), even though it looks like two nested loops. - The stock span of a day is how many days in a row, ending today, had a price no higher than today’s. The stack keeps earlier days with higher prices. After popping days with lower or equal prices, the day on top is the last higher price, and the span is the distance to it. On the last day (85), only the first day (100) was higher, so the span is 6.
Largest Rectangle in a Histogram
#include <stdio.h>
/* Largest rectangle in a histogram, using an increasing stack: O(n) */
static long largest_rectangle(const int *h, int n, int *best_l, int *best_r) {
int stack[128], top = -1;
long best = 0;
for (int i = 0; i <= n; i++) {
int cur = i == n ? 0 : h[i]; /* a final 0 empties the stack */
while (top >= 0 && h[stack[top]] >= cur) {
int height = h[stack[top--]];
int left = top >= 0 ? stack[top] + 1 : 0; /* first bar this one can extend to */
long area = (long)height * (i - left);
if (area > best) { best = area; *best_l = left; *best_r = i - 1; }
}
stack[++top] = i;
}
return best;
}
int main(void) {
int h[] = {2, 1, 5, 6, 2, 3};
int n = sizeof h / sizeof h[0], l = 0, r = 0;
long area = largest_rectangle(h, n, &l, &r);
printf("largest rectangle: area %ld, bars %d..%d\n", area, l, r);
/* Picture of the bars */
long rect_h = area / (r - l + 1); /* height of the best rectangle */
for (int level = 6; level >= 1; level--) {
for (int i = 0; i < n; i++) {
char c = ' ';
if (h[i] >= level) c = (i >= l && i <= r && level <= rect_h) ? '#' : '|';
printf(" %c", c);
}
printf("\n");
}
for (int i = 0; i < n; i++) printf(" %d", h[i]);
printf("\n");
int city[] = {3, 3, 3, 3, 1, 4, 4};
printf("skyline: area %ld\n", largest_rectangle(city, 7, &l, &r));
return 0;
}
Output
largest rectangle: area 10, bars 2..3
|
# #
# #
# # |
| # # | |
| | # # | |
2 1 5 6 2 3
skyline: area 12
- Each bar has width 1. The task is to find the largest rectangle that fits inside the bars. The
#marks show the answer: height 5 across bars 2 and 3, area 10. - This time the stack is increasing. When a shorter bar arrives, taller bars on the stack cannot extend any further to the right, so each popped bar’s best rectangle is calculated at once.
- For a popped bar, the right edge is just before the current bar, and the left edge is just after the bar now on top of the stack, the nearest shorter bar to the left.
- A final imaginary bar of height 0 (when
i == n) pops everything that is left, so no bar is forgotten. - In the skyline, the four buildings of height 3 give area 12, beating the two of height 4 (area 8).
- The same technique solves the “largest rectangle of 1s in a binary matrix” problem by treating each row as a histogram.
Which Stack Order to Use
| Problem | Stack order (bottom to top) | Pop when |
|---|---|---|
| Next greater element | Decreasing | New value is greater |
| Next smaller element | Increasing | New value is smaller |
| Stock span (previous greater) | Decreasing | Top is less than or equal |
| Largest rectangle | Increasing heights | New bar is lower or equal |
| Daily temperatures (days until warmer) | Decreasing | New temperature is higher |
Common Mistakes
- Pushing values instead of indexes when the answer needs distances or positions.
- Forgetting the leftover elements on the stack at the end.
- Using
<where<=is needed (or the reverse), which changes how equal values are handled. - Calling it O(n2) because of the nested loop; count pushes and pops instead.
Practice Exercises
Exercise 1. For temperatures {30, 32, 31, 35, 33}, how many days must you wait after each day for a warmer one?
Show answer
{1, 2, 1, 0, 0}. Use the next greater element code, but store i - stack[top] instead of the value, and 0 when there is none.
Exercise 2. Change next_greater to find the next smaller element.
Show answer
Flip the comparison: pop while a[stack[top]] > a[i]. The stack is then increasing from bottom to top.
Frequently Asked Questions
What is the difference between a monotonic stack and a monotonic queue?
A monotonic stack adds and removes at one end and answers “next or previous greater/smaller” questions. A monotonic queue (a deque) also removes old elements from the front, which suits sliding windows, as in the sliding window maximum shown in the deque lesson.
How do I handle a circular array?
Loop over the array twice (indexes 0 to 2n − 1, using i % n), but only push indexes during the first pass. Elements near the end can then find greater elements near the start.
Summary
- A monotonic stack keeps its values in sorted order by popping as needed.
- Each element is pushed and popped once, so the algorithm is O(n).
- Decreasing stacks find next greater elements; increasing stacks find next smaller ones.
- It solves next greater element, stock span and the histogram rectangle.
Next: Bit Manipulation in C.
