Skip to main content

3.5 Monotonic Stacks & Next Greater Element Patterns

πŸ“šModule 03 β€’ Stacks & ApplicationsTopic 3.5⏱️13 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 O(n2)\mathcal{O}(n^2) 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 Θ(n)\Theta(n) amortized time.


πŸ“Š 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 than A[top]: pop idx = stack[top--], record ans[idx] = A[i], and keep popping until A[top] >= A[i] (or empty).
  • Push current index i onto 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 i is pushed onto the stack EXACLY ONCE (nn pushes total).
  • Because a popped index NEVER re-enters the stack, total pop() iterations across the ENTIRE for loop cannot exceed nn!
  • Total stack operations ≀2n=Θ(n)\le 2n = \mathbf{\Theta(n)}!

Choosing Stack Ordering by Query Type​

Query GoalStack Order (Bottom β†’\to Top)Pop Condition When Scanning A[i]Example Application
Next Greater ElementDecreasingA[top] < A[i]Stock Price Breakout, Next Warmer Day
Next Smaller ElementIncreasingA[top] > A[i]Largest Rectangle in Histogram (width bounds!)
Stock Span (Prev ≀\le)DecreasingA[top] <= A[i]Consecutive prior days with price ≀\le 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​

πŸ“Problem Statement: Full Trace of Next Greater Element & Stock Spantheorem

Given prices array A = [100, 80, 60, 70, 60, 75, 85] (n=7n = 7):

  1. Compute the Next Greater Element output array using a Monotonic Decreasing Stack (-1 if none exists).
  2. Compute the Stock Span array (count of consecutive prior days including today with price ≀A[i]\le A[i]).

Step-by-Step Solution:​

  1. 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 -> pop 2 (ans[2]=70); push 3 -> 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 < 80 stops -> Stack [0, 1, 5].
    • i=6 (85): 85 > 75 (ans[5]=85), 85 > 80 (ans[1]=85); 85 < 100 stops -> Stack [0, 6].
    • Remaining [0, 6] have no greater element -> ans = [-1, 85, 70, 75, 75, 85, -1].
  2. Stock Span Trace (<= pops toward Previous Strictly Greater):

    • i=0 (100): prev greater none β€…β€ŠβŸΉβ€…β€Š0+1=1\implies 0 + 1 = 1
    • i=1 (80): stops at 0 (100) β€…β€ŠβŸΉβ€…β€Š1βˆ’0=1\implies 1 - 0 = 1
    • i=2 (60): stops at 1 (80) β€…β€ŠβŸΉβ€…β€Š2βˆ’1=1\implies 2 - 1 = 1
    • i=3 (70): pops 2 (60), stops at 1 (80) β€…β€ŠβŸΉβ€…β€Š3βˆ’1=2\implies 3 - 1 = 2
    • i=4 (60): stops at 3 (70) β€…β€ŠβŸΉβ€…β€Š4βˆ’3=1\implies 4 - 3 = 1
    • i=5 (75): pops 4 (60), 3 (70), stops at 1 (80) β€…β€ŠβŸΉβ€…β€Š5βˆ’1=4\implies 5 - 1 = 4
    • i=6 (85): pops 5 (75), 1 (80), stops at 0 (100) β€…β€ŠβŸΉβ€…β€Š6βˆ’0=6\implies 6 - 0 = 6
    • Span Result: [1, 1, 1, 2, 1, 4, 6].

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Why should a Monotonic Stack almost always store array indices rather than raw element values?
    • Knowing idx gives 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.
  2. How do you handle a circular array (Next Greater Element II wrapping around)?
    • Loop for (int i = 0; i < 2 * n; i++) using arr[i % n] (pushing indices only while i < n), scanning twice cleanly in Θ(n)\Theta(n)!
Common Interview Traps: Architectural Trade-Offs
  • 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, else 70 falsely reports 70 as greater!).
  • Missing Final Sentinel Flush (i = n with Height 0): In Largest Rectangle in Histogram, bars remaining in the increasing stack at EOF stretch all the way to array end n β€” always append a synthetic zero-height barrier (or flush the stack manually after the loop)!
  • Mistaking while Inside for for O(n2)\mathcal{O}(n^2): Total pops across ALL iterations combined never exceed nn, capping overall time strictly at Θ(n)\Theta(n)!

πŸš€ Navigation & Next Steps​

Congratulations on finishing Module 03 (Stacks & Applications)! Next, we trade LIFO ordering for FIFO Queue fairness in Module 04 β€” Queues & Buffers.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.