|
| 1 | +""" |
| 2 | +739. Daily Temperatures |
| 3 | +
|
| 4 | +https://leetcode.com/problems/daily-temperatures |
| 5 | +
|
| 6 | +NOTES |
| 7 | + * Traverse the array from the right and use a monotonically decreasing stack. |
| 8 | +
|
| 9 | +Stacks vs. Queues |
| 10 | +----------------- |
| 11 | +A monotonic stack and a monotonic queue are similar data structures that |
| 12 | +maintain elements in a monotonic order (either strictly decreasing or strictly |
| 13 | +increasing), but they differ in their operations and use cases. |
| 14 | +
|
| 15 | + Monotonic Stack |
| 16 | + * Elements are added/removed from the same end (LIFO - Last In, First Out). |
| 17 | + * Uses push and pop operations. |
| 18 | + * When adding a new element, pops existing elements that violate the |
| 19 | + monotonic property. |
| 20 | + * Typically used to find the "next greater/smaller element" or to solve |
| 21 | + problems involving ranges where elements dominate others. |
| 22 | +
|
| 23 | + Monotonic Queue |
| 24 | + * Elements are added at one end and removed from the other (FIFO - First |
| 25 | + In, First Out). |
| 26 | + * Uses enqueue (append) at one end and dequeue (popleft) from the other. |
| 27 | + * When adding a new element, removes existing elements that violate the |
| 28 | + monotonic property. |
| 29 | + * Often used for sliding window problems to efficiently track |
| 30 | + maximum/minimum values within the window. |
| 31 | +
|
| 32 | +In Python, a deque can be used for both stacks and queues, however, it is |
| 33 | +important to differentiate when/how each data structure should be used: |
| 34 | + * Stack: push, pop |
| 35 | + * Queue: append, popleft |
| 36 | +""" |
| 37 | + |
| 38 | +from collections import deque |
| 39 | + |
| 40 | + |
| 41 | +class Solution: |
| 42 | + def dailyTemperatures(self, temperatures: list[int]) -> list[int]: |
| 43 | + stack: deque[int] = deque() |
| 44 | + ans: list[int] = [0] * len(temperatures) |
| 45 | + |
| 46 | + for i in reversed(range(len(temperatures))): |
| 47 | + while stack and temperatures[i] >= temperatures[stack[-1]]: |
| 48 | + stack.pop() |
| 49 | + if stack and temperatures[i] < temperatures[stack[-1]]: |
| 50 | + ans[i] = stack[-1] - i |
| 51 | + stack.append(i) |
| 52 | + |
| 53 | + return ans |
0 commit comments