See how a monotonic stack calculates the number of days until a warmer temperature in one pass.
Monotonic Stack LeetCode 739 ↗ Mediumtemperatures, return an array answer such that
answer[i] is the number of days you have to wait after the
ith day to get a warmer temperature. If there is no future day for which this is
possible, keep answer[i] == 0.temperatures = [73,74,75,71,69,72,76,73], the answer is
[1,1,4,2,1,1,0,0].
fun dailyTemperatures(temperatures: IntArray): IntArray { val n = temperatures.size val answer = IntArray(n) // initialized to 0 val stack = ArrayDeque<Int>() // indices for (i in temperatures.indices) { while (stack.isNotEmpty() && temperatures[stack.last()] < temperatures[i]) { val j = stack.removeLast() answer[j] = i - j } stack.addLast(i) } return answer}
A monotonic decreasing stack keeps track of indices whose temperatures have not yet found a warmer future day. The stack always holds indices in order such that their corresponding temperatures are non-increasing from bottom to top. When a new temperature is warmer than the top of the stack, we have found the answer for that stack entry.
answer array of zeros and an empty stack.i: Compare the current temperature with the temperature at the index on top of the stack.j from the stack and set answer[j] = i - j (the number of days waited).i onto the stack — it is now waiting for its own warmer day.0.The stack maintains a decreasing order of temperatures. Each time we push a new index, we first pop all indices with temperatures strictly less than the current one. This guarantees that the stack top always holds the most recently seen temperature that is still ≥ the current temperature.
Each index is pushed onto the stack exactly once and popped at most once, giving O(n) total
stack operations. The stack and answer array each use O(n) space.