今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

The Monotonic Stack: Like Gandalf's Staff for Array Problems

Timevolt 2026年06月24日 05:16 2 次阅读 来源:Dev.to

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 alrea

本文内容来源于互联网,版权归原作者所有
查看原文