Daily Temperatures in Java: Explanation & Practice

Days until warmer temperature

Problem summary

Given an array of temperatures, return how many days you have to wait for a warmer temperature. Return 0 if no warmer day.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] temps = {73, 74, 75, 71, 69, 72, 76, 73};
        
        // Same as next greater element!
        // Store indices, calculate distance
        // Print: 1 1 4 2 1 1 0 0
    }
}

Expected output and test cases

  • [73,74,75,71,69,72,76,73]
    1 1 4 2 1 1 0 0
  • [30,40,50,60]
    1 1 1 0
  • [30,20,10]
    0 0 0

Hints

  1. Use monotonic decreasing stack storing indices
  2. When we find a warmer day, pop all cooler days
  3. Answer for popped index = current index - popped index
  4. Remaining in stack have no warmer day → answer is 0

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler