Monotonic Stack: Solving the 'Daily Temperatures' Problem

Hero image for Monotonic Stack: Solving the 'Daily Temperatures' Problem. Image by Bianca Ackermann.
Hero image for 'Monotonic Stack: Solving the 'Daily Temperatures' Problem.' Image by Bianca Ackermann.

Daily Temperatures is a very good stack problem because the stack is doing something more interesting than simple bracket matching. We are given an array of temperatures, and for each day we need to know how many days we must wait until a warmer temperature appears. If no warmer day exists, the answer is 0.

The bruteforce solution is obvious enough: for each day, scan forward until we find a warmer value. That is easy to write and easy to explain, but it repeats the same work constantly. The better solution comes from keeping a stack of days that are still waiting for their answer.

That is where the monotonic stack pattern comes in.


What Makes This a Monotonic Stack Problem

We keep a stack of indices whose temperatures have not yet found a warmer future day.

The useful rule is that the stack stays in decreasing temperature order. That means:

  • the top of the stack is the most recent unresolved day
  • if today's temperature is warmer than the temperature at the top index, we can resolve that earlier day immediately

And not just one earlier day. We keep popping whilst today's temperature is warmer than the unresolved temperature on the top of the stack.

That is why this pattern is called monotonic. The stack maintains a deliberate order so comparisons become cheap and structured.


A Practical TypeScript Solution

export const dailyTemperatures = (temperatures: number[]): number[] => {  const result = new Array<number>(temperatures.length).fill(0);  const pendingIndices: number[] = [];  for (let index = 0; index < temperatures.length; index += 1) {    while (      pendingIndices.length > 0 &&      temperatures[index] >        temperatures[pendingIndices[pendingIndices.length - 1]]    ) {      const previousIndex = pendingIndices.pop();      if (previousIndex === undefined) {        break;      }      result[previousIndex] = index - previousIndex;    }    pendingIndices.push(index);  }  return result;};

Why Storing Indices Matters More than Storing Temperatures

This is the detail people often gloss over too quickly.

If we stored only the temperatures themselves, we would know which earlier values had been beaten, but we would not know where to write the answer or how many days had passed.

The problem is asking for distances, not just comparisons. That means indices are the real state we need. From an index we can get:

  • the earlier temperature value
  • the position where the answer belongs
  • the number of days waited

That is why the stack stores previousIndex, not the temperature directly.


Walking through the Idea with a Small Example

Take:

[73, 74, 75, 71, 69, 72, 76, 73]

Start with index 0 on the stack.

At index 1, temperature 74 is warmer than 73, so index 0 can be resolved:

  • result[0] = 1

At index 2, temperature 75 is warmer than 74, so index 1 is resolved:

  • result[1] = 1

Later, when we reach 72, it resolves both 69 and 71 because it is warmer than both of those pending days.

That is the power of the monotonic stack. One new value can resolve several older positions in one tight loop.


Why the Stack Stays Decreasing

When a new temperature arrives, we pop every earlier day that it can resolve. After that, the remaining stack top, if any, must still be warmer than or equal to the current temperature. Then we push the current index.

That means the unresolved temperatures in the stack stay in decreasing order from bottom to top.

This ordering is not just a nice property. It is what makes the repeated popping safe and efficient.


Common Mistakes

Pushing Temperatures Instead of Indices

That loses the daydistance information and makes the result array much harder to populate correctly.

Forgetting That Equal Temperatures Do Not Count

The question asks for a warmer day, not a day that is merely as warm. That is why the comparison is > rather than >=.

Thinking Each Item Might Be Popped Many Times

Each index is pushed once and popped at most once. That is why the solution stays linear.


Complexity and Why It is Better than It Looks

At first glance, the while loop can make the algorithm look as if it might become quadratic. It does not.

Each index:

  • enters the stack once
  • leaves the stack once

So the total time complexity is O(n), and the extra space is O(n) for the stack.

That "push once, pop once" reasoning is one of the most useful habits for understanding monotonic stack problems generally.


Wrapping up

Daily Temperatures is a strong monotonicstack problem because it shows what stacks are good at beyond nesting syntax. The stack is acting as a holding area for unresolved days, and the monotonic ordering ensures that one warmer day can resolve exactly the right earlier positions efficiently.

Key Takeaways

  • The stack stores unresolved indices, not raw temperatures.
  • A warmer current temperature resolves earlier cooler days at the top of the stack.
  • Each index is pushed and popped at most once, which keeps the solution linear.

Once that unresolveddays mental model clicks, the problem feels much less like a trick and much more like a neat way of delaying answers until the right evidence arrives.


Categories:

  1. Algorithms
  2. Data Structures
  3. Development
  4. Guides
  5. JavaScript
  6. LeetCode
  7. TypeScript