739. Daily Temperatures
Asked at 25Amazon58Bloomberg57Microsoft54Google48Meta45Anduril74Chime73tcs42Goldman Sachs40Disney88Agoda87Zoho86Grab76Swiggy69Morgan Stanley64Tekion63TikTok63josh technology58Intuit52Flipkart43Walmart Labs43Nvidia39Infosys39Yandex28Oracle27
Problem
For each day, return how many days you must wait after it for a strictly warmer temperature, or 0 if none comes.
Example: [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0]
Constraints: n ≤ 10⁵.
Decreasing stack of indices. A warmer day pops every colder index and fills its wait = i − j.
temps 73 74 75 71 69 72 76 73
i=5 (72): pops 69(idx4)->1, 71(idx3)->2 stack [75, 72]
i=6 (76): pops 72->1, 75->4 stack [76]
Complexity: O(n).
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res, st = [0] * len(temperatures), []
for i, t in enumerate(temperatures):
while st and temperatures[st[-1]] < t:
j = st.pop()
res[j] = i - j
st.append(i)
return res
assert Solution().dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert Solution().dailyTemperatures([30, 40, 50, 60]) == [1, 1, 1, 0]
assert Solution().dailyTemperatures([60, 50, 40]) == [0, 0, 0]
class Solution {
public int[] dailyTemperatures(int[] t) {
int[] res = new int[t.length];
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < t.length; i++) {
while (!st.isEmpty() && t[st.peek()] < t[i]) {
int j = st.pop();
res[j] = i - j;
}
st.push(i);
}
return res;
}
}
func dailyTemperatures(temperatures []int) []int {
res, st := make([]int, len(temperatures)), []int{} // stack of indices, temps decreasing
for i, t := range temperatures {
for len(st) > 0 && temperatures[st[len(st)-1]] < t {
j := st[len(st)-1]
st = st[:len(st)-1]
res[j] = i - j
}
st = append(st, i)
}
return res
}