← Stacks & Queues

Daily Temperatures

Medium
Python
def daily_temperatures(temps):
    stack=[]; res=[0]*len(temps)
    for i,t in enumerate(temps):
        while stack and temps[stack[-1]]<t:
            idx=stack.pop(); res[idx]=i-idx
        stack.append(i)
    return res
Java
public int[] dailyTemperatures(int[] temps){
    Stack<Integer> stack=new Stack<>();
    int[] res=new int[temps.length];
    for(int i=0;i<temps.length;i++){
        while(!stack.isEmpty()&&temps[stack.peek()]<temps[i]){
            int idx=stack.pop(); res[idx]=i-idx;
        } stack.push(i);
    } return res;
}

Key Insight

Monotonic stack. 'while stack' vs !isEmpty(). enumerate vs index.

Python → Java Differences

  • 'while stack' vs !isEmpty()
  • Monotonic stack identical
  • enumerate vs manual index
Python
def daily_temperatures(temps):
    stack=[]; res=[0]*len(temps)
    for i,t in enumerate(temps):
        while stack and temps[stack[-1]]<t:
            idx=stack.pop(); res[idx]=i-idx
        stack.append(i)
    return res
Java
public int[] dailyTemperatures(int[] temps){
    Stack<Integer> stack=new Stack<>();
    int[] res=new int[temps.length];
    for(int i=0;i<temps.length;i++){
        while(!stack.isEmpty()&&temps[stack.peek()]<temps[i]){
            int idx=stack.pop(); res[idx]=i-idx;
        } stack.push(i);
    } return res;
}

Algorithm Steps

1. Monotonic decreasing stack
2. Pop when warmer found
3. Record gap