惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
J
Java Code Geeks
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
腾讯CDC
D
DataBreaches.Net
Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
V
V2EX
F
Fortinet All Blogs
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
Jina AI
Jina AI
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
A
About on SuperTechFans
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
B
Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Monotonic Stack: Like Gandalf's Staff for Array Problems
Timevolt · 2026-06-24 · via DEV Community

The Quest Begins (The "Why")

Honestly, I still remember the first time I stared at the Daily Temperatures problem on LeetCode and felt like I was trying to crack a vault with a toothpick. The brute‑force solution — two nested loops, checking every future day for a warmer temperature — was simple to write, but it timed out on the larger test cases. I spent an hour tweaking loops, adding early breaks, and even trying to memoize results, only to watch the same red “Time Limit Exceeded” banner flash again.

I was frustrated, but more than that, I was curious. Why did this problem feel so repetitive? Every element seemed to be asking the same question: “What’s the next greater value to my right?” If I could answer that for each index in a single pass, the whole thing would collapse into O(n). That’s when I remembered a weird little data structure I’d seen in a textbook — the monotonic stack — and realized it might be the magic wand I needed.

The Revelation (The Insight)

Here’s the thing: a monotonic stack isn’t just a stack with a funny name; it’s a way to capture relationships between elements without ever looking backward more than once.

Imagine you’re walking through a line of people sorted by height, and you want to know, for each person, who is the first taller person standing ahead of them. If you keep a stack of people whose heights are strictly decreasing as you move from left to right, then whenever you see a new person taller than the one on top of the stack, you’ve just found the answer for that stacked person: the current person is their “next greater.” You pop them off, record the distance, and keep going. Because each index is pushed once and popped at most once, the total work is linear.

The same idea works for “next smaller,” “previous greater,” or any problem where you need the nearest element that satisfies a monotonic condition. The stack does the heavy lifting of remembering candidates that could still be relevant, discarding the ones that are already dominated by a newer element. It’s like having Gandalf’s staff: you point it at the array, and the staff instantly reveals the hidden order without you having to swing a sword at every pair.

Wielding the Power (Code & Examples)

Before: The Brute‑Force Struggle

def daily_temperatures_bruteforce(temps):
    n = len(temps)
    answer = [0] * n
    for i in range(n):
        for j in range(i + 1, n):
            if temps[j]temps[j] > temps[i]:
                answer[i] = j - i
                break
    return answer

Ouch — O(n²) time, O(1) extra space. It works on tiny inputs, but any realistic test set makes it crawl.

After: Monotonic Stack to the Rescue

def daily_temperatures(temps):
    n = len(temps)
    answer = [0] * n
    stack = []               # will store indices with decreasing temperatures

    for i, t in enumerate(temps):
        # While current temp breaks the decreasing order,
        # we have found the next greater for the stacked indices.
        while stack and temps[stack[-1]] < t:
            prev = stack.pop()
            answer[prev] = i - prev
        stack.append(i)

    # Remaining indices have no warmer day; answer stays 0.
    return answer

Why it’s O(n): each index is pushed onto stack once and popped at most once. The inner while loop may look like it could be nested, but the total number of iterations across the whole run is bounded by n. Space is O(n) in the worst case (a strictly decreasing temperature series).

Another Classic: Largest Rectangle in Histogram

Same principle, just flipped: we need the previous smaller and next smaller for each bar.

def largest_rectangle_area(heights):
    stack = []          # increasing heights
    max_area = 0
    # Append a sentinel height 0 to flush the stack at the end
    for i, h in enumerate(heights + [0]):
        while stack and heights[stack[-1]] > h:
            height = heights[stack.pop()]
            # width is current index i minus index of new top minus 1
            width = i if not stack else i - stack[-1] - 1
            max_area = max(max_area, height * width)
        stack.append(i)
    return max_area

Again, each bar is pushed and popped once → O(n) time, O(n) space.

Traps to Avoid on the Quest

  • Equality handling: If you need “next greater or equal,” change the comparison to <= (or >= for smaller). Mixing up strict vs. non‑strict breaks the invariant.
  • Direction confusion: Decide whether you’re scanning left‑to‑right for next greater or right‑to‑left for previous greater, and keep the stack order consistent.
  • Cleaning up: After the main loop, don’t forget to pop the remaining elements and assign their answer (often 0 or a default).

Why This New Power Matters

Once you internalize the monotonic stack trick, a whole family of interview‑favorite problems becomes trivial:

  • Daily Temperatures / Next Greater Element
  • Largest Rectangle in Histogram
  • Sum of Subarray Minimums
  • Maximum Width Ramp
  • Trapping Rain Water

You’ll stop writing those dreadful double‑loops and start spotting the pattern: “I need the nearest element that beats (or is beaten by) the current one under a monotonic condition.” It’s like gaining a new spell slot in your coding repertoire — suddenly, the boss fights feel manageable.

And the best part? The intuition transfers beyond arrays. Monotonic stacks appear in parsing (e.g., evaluating expressions), in graph algorithms (like finding next greater node in a tree), and even in computational geometry. Once you see the pattern, you’ll start spotting it everywhere.

Your Turn – The Next Challenge

Here’s a fun quest for you: Solve “Sum of Subarray Minimums” (LeetCode 907) using a monotonic stack. Try to derive why each element contributes left * right * value to the total, where left is the distance to the previous strictly smaller element and right is the distance to the next smaller-or-equal element.

Drop your solution or any questions in the comments — let’s see who can wield the staff most elegantly! Happy stacking!