3.5 Monotonic Stacks & Next Greater Element Patterns
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Skyscrapers Blocking a Horizon Lineβ
Stand looking left-to-right down a street of skyscrapers (heights = [4, 2, 5, 8]). Suppose you ask each building: "Which building further down the street is the first one taller than you?" Whenever a tall building (5) appears after shorter ones (4, 2), 5 is immediately the answer for both 2 and 4 β AND because 5 completely blocks anyone shorter behind it from matching future buildings, shorter buildings get permanently eliminated from sight!
π» Bridging to Computer Science: Ordered-Invariant Linear Scansβ
Brute-force "Next Greater Element" scans check every suffix pair in time. A Monotonic Stack preserves strictly decreasing (or increasing) active elements on the stack by popping overshadowed items immediately upon arrival β resolving Next Greater/Smaller boundaries across an entire array in strictly amortized time.
πTable of Contents
π Monotonic Decreasing Stack Mechanics (Next Greater Element)β
To find the first greater value to the right of every A[i], keep stack indices ordered decreasing bottom-to-top:
- Whenever incoming
A[i]is strictly greater thanA[top]: popidx = stack[top--], recordans[idx] = A[i], and keep popping untilA[top] >= A[i](or empty). - Push current index
ionto the stack. Any indices left inside at EOF have-1(no taller element to their right!).
Amortized Linear Time Proof (Linear vs Quadratic)β
Even though a while loop sits nested inside the outer for (i = 0..n-1) loop:
- Every index
iis pushed onto the stack EXACLY ONCE ( pushes total). - Because a popped index NEVER re-enters the stack, total
pop()iterations across the ENTIREforloop cannot exceed ! - Total stack operations !
Choosing Stack Ordering by Query Typeβ
| Query Goal | Stack Order (Bottom Top) | Pop Condition When Scanning A[i] | Example Application |
|---|---|---|---|
| Next Greater Element | Decreasing | A[top] < A[i] | Stock Price Breakout, Next Warmer Day |
| Next Smaller Element | Increasing | A[top] > A[i] | Largest Rectangle in Histogram (width bounds!) |
| Stock Span (Prev ) | Decreasing | A[top] <= A[i] | Consecutive prior days with price today |
π» C Implementation: Linear-Time Next Greater Elementβ
void nextGreaterElements(const int arr[], int ans[], int n) {
int stack[n];
int top = -1;
for (int i = 0; i < n; i++) ans[i] = -1;
for (int i = 0; i < n; i++) {
while (top >= 0 && arr[stack[top]] < arr[i]) {
int resolvedIdx = stack[top--];
ans[resolvedIdx] = arr[i]; // First greater to the right!
}
stack[++top] = i; // Always store INDICES!
}
}
π Real-World Production Context: Histogram Geometry & Spansβ
Monotonic Stacks in Algorithms & Analytics
Any single-pass boundary search for the nearest larger or smaller barrier reduces cleanly to a Monotonic Stack
Financial Stock Span & Trading Breakouts
Time-Series Signals- Computes how many consecutive prior days maintained price <= today's close in O(n) streaming time.
- Powers real-time sliding support/resistance detectors.
Daily Wait-Time Forecasts
Telemetry Alerts- Computes exact wait intervals until the next warmer reading or CPU threshold spike.
- Storing indices rather than raw values unlocks distance = i - resolvedIdx directly.
Largest Rectangle in Histogram
2D Layout & Image Bounding- Monotonic INCREASING stack discovers both Left and Right shorter bar boundaries in one single pass!
- Unlocks Maximal Binary Submatrix detection inside UI & document layout engines.
π Numerical Applications & Worked Examplesβ
Given prices array A = [100, 80, 60, 70, 60, 75, 85] ():
- Compute the Next Greater Element output array using a Monotonic Decreasing Stack (
-1if none exists). - Compute the Stock Span array (count of consecutive prior days including today with price ).
Step-by-Step Solution:β
-
Next Greater Element Trace (Storing Indices):
i=0 (100): Stack[0].i=1 (80):80 < 100-> Stack[0, 1].i=2 (60): Stack[0, 1, 2].i=3 (70):70 > A[2]=60-> pop2(ans[2]=70); push3-> Stack[0, 1, 3].i=4 (60): Stack[0, 1, 3, 4].i=5 (75):75 > 60(ans[4]=75),75 > 70(ans[3]=75);75 < 80stops -> Stack[0, 1, 5].i=6 (85):85 > 75(ans[5]=85),85 > 80(ans[1]=85);85 < 100stops -> Stack[0, 6].- Remaining
[0, 6]have no greater element ->ans = [-1, 85, 70, 75, 75, 85, -1].
-
Stock Span Trace (
<=pops toward Previous Strictly Greater):i=0 (100): prev greater nonei=1 (80): stops at0 (100)i=2 (60): stops at1 (80)i=3 (70): pops2 (60), stops at1 (80)i=4 (60): stops at3 (70)i=5 (75): pops4 (60), 3 (70), stops at1 (80)i=6 (85): pops5 (75), 1 (80), stops at0 (100)- Span Result:
[1, 1, 1, 2, 1, 4, 6].
π― Exam & Interview Pitfall Checkβ
- Why should a Monotonic Stack almost always store array indices rather than raw element values?
- Knowing
idxgives you BOTH the value (arr[idx]) AND its exact position distance (i - idx) for Stock Span, Daily Temperatures, and Histogram widths! Storing raw values loses positional offsets permanently.
- Knowing
- How do you handle a circular array (
Next Greater Element IIwrapping around)?- Loop
for (int i = 0; i < 2 * n; i++)usingarr[i % n](pushing indices only whilei < n), scanning twice cleanly in !
- Loop
- Forgetting
<vs.<=Strictness on Equal Elements: In Stock Span, days with equal prices ([70, 70]) extend the span (<=MUST pop!). In strict Next Greater, equal elements (70 == 70) do NOT satisfy strict greater (<MUST NOT pop, else70falsely reports70as greater!). - Missing Final Sentinel Flush (
i = nwith Height0): In Largest Rectangle in Histogram, bars remaining in the increasing stack at EOF stretch all the way to array endnβ always append a synthetic zero-height barrier (or flush the stack manually after the loop)! - Mistaking
whileInsideforfor : Total pops across ALL iterations combined never exceed , capping overall time strictly at !
π Navigation & Next Stepsβ
Congratulations on finishing Module 03 (Stacks & Applications)! Next, we trade LIFO ordering for FIFO Queue fairness in Module 04 β Queues & Buffers.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.