LeetCode 75

Daily Temperatures

Problem
LC 739
Topic
Monotonic Stack
File
official75_LC739DailyTemperatures.java
Path
pkg5leetcode/official75/official75_LC739DailyTemperatures.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC739DailyTemperatures.java
Approach
Monotonic decreasing stack of indices.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC739DailyTemperatures.java
1package pkg5leetcode.official75;2 3/*4 * Daily Temperatures | LC 7395 * APPROACH: Monotonic decreasing stack of indices.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC739DailyTemperatures {11    static int[] dailyTemperatures(int[] temperatures) {12        int n = temperatures.length;13        int[] res = new int[n];14        Deque<Integer> st = new ArrayDeque<>();15        for (int i = 0; i < n; i++) {16            while (!st.isEmpty() && temperatures[i] > temperatures[st.peekLast()]) {17                int idx = st.pollLast();18                res[idx] = i - idx;19            }20            st.addLast(i);21        }22        return res;23    }24 25    public static void main(String[] args) {26        check(Arrays.equals(dailyTemperatures(new int[]{73,74,75,71,69,72,76,73}),27                new int[]{1,1,4,2,1,1,0,0}), "case1");28        check(Arrays.equals(dailyTemperatures(new int[]{30,40,50,60}),29                new int[]{1,1,1,0}), "case2");30        System.out.println("all tests passed");31    }32 33    static void check(boolean cond, String name) {34        if (!cond) throw new AssertionError("FAILED: " + name);35        System.out.println("  PASS " + name);36    }37}