Tags: leetcode python stack java
Given an array of integers temperatures represents the daily temperatures, 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 instead.
Time Limit Exceeded since complexity is O(N²)
A regular stack follows LIFO (Last In, First Out). You push and pop from the top.
A monotonic stack , we maintain either increasing or decreasing order. Use decreasing monotonic stack to find next greater element. Use increasing monotonic stack to find next smallest element.
We will use monotonic decreasing stack to find next largest element
Time complexity O(n)
Why time complexity is O(N²)?
for i in range(n): # ← loop runs n times
while something: # ← looks like this could run up to n times too
do stuff
The outer for loop runs n times (where n is the length of temperatures).
Each index is pushed onto the stack at most once. This contributes at most n push operations in total.
Each index is popped from the stack at most once. This contributes at most n pop operations in total.
Iteration | Index | Temperature | Operations | Stack State After | Result Update |
---|---|---|---|---|---|
0 | 0 | 73 | Stack is empty → push index 0 | [0] | [0, 0, 0, 0, 0, 0, 0, 0] |
1 | 1 | 74 | Compare 74 with temperature at index 0 (73): 74 > 73 → pop index 0, set result[0] = 1; then push index 1 | [1] | [1, 0, 0, 0, 0, 0, 0, 0] |
2 | 2 | 75 | Compare 75 with temperature at index 1 (74): 75 > 74 → pop index 1, set result[1] = 1; then push index 2 | [2] | [1, 1, 0, 0, 0, 0, 0, 0] |
3 | 3 | 71 | Compare 71 with temperature at index 2 (75): 71 is not > 75 → push index 3 | [2, 3] | No change |
4 | 4 | 69 | Compare 69 with temperature at index 3 (71): 69 is not > 71 → push index 4 | [2, 3, 4] | No change |
5 | 5 | 72 |
|
[2, 5] | result[4]=1, result[3]=2 |
6 | 6 | 76 |
|
[6] | result[5]=1, result[2]=4 |
7 | 7 | 73 | Compare 73 with temperature at index 6 (76): 73 is not > 76 → push index 7 | [6, 7] | No change |