Skip to content

Commit a2b9fe1

Browse files
Add Daily Temperatures interview drill (monotonic stack)
Third runnable drill for the interviewDrills/ section. Pattern is the canonical "next greater element" framing: a single monotonic-decreasing stack of indices walks each day in O(n) and writes the gap to the answer array when a warmer day arrives. - DailyTemperatures.java: O(n) implementation with main() assertions covering increasing, decreasing, mixed, repeated-tie, single-day, and empty inputs. - daily-temperatures.md: pattern callout, what to say in the interview, common traps (storing temps instead of indices, using >=, reaching for a heap), edge cases, and run instructions. - interviewDrills/README.md: link the drill into the index table. Verified locally: javac interviewDrills/DailyTemperatures.java java -cp interviewDrills DailyTemperatures -> All DailyTemperatures drill checks passed. Jekyll site build runs in the gh-pages PR check. Co-Authored-By: Paperclip <noreply@paperclip.ing>
1 parent ed2aa73 commit a2b9fe1

3 files changed

Lines changed: 172 additions & 0 deletions

File tree

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import java.util.Arrays;
2+
import java.util.ArrayDeque;
3+
import java.util.Deque;
4+
5+
/**
6+
* MAANG screen drill: Daily Temperatures (monotonic decreasing stack).
7+
*
8+
* Interview signal:
9+
* - Do you recognize "next greater element" as a monotonic-stack pattern
10+
* instead of brute-force O(n^2) double loops?
11+
* - Do you store indices on the stack (not values), so you can compute the
12+
* distance between the warmer day and the day waiting for it?
13+
*
14+
* Problem:
15+
* Given an array of integer daily temperatures, return an array answer where
16+
* answer[i] is the number of days you have to wait after day i to get a
17+
* warmer temperature. If no future day is warmer, answer[i] = 0.
18+
*
19+
* Approach:
20+
* 1. Walk left to right keeping a stack of indices whose answer is unknown.
21+
* 2. While the current temperature is strictly greater than the temperature
22+
* at the top index, that top index has just found its warmer day -- pop
23+
* it and write the gap (currentIndex - poppedIndex) into answer.
24+
* 3. Push the current index. Stack stays monotonically decreasing in
25+
* temperature, so each index is pushed and popped at most once.
26+
*
27+
* Complexity:
28+
* - Time: O(n). Each index is pushed and popped at most once.
29+
* - Space: O(n) for the stack and the output array.
30+
*/
31+
public class DailyTemperatures {
32+
33+
public static int[] dailyTemperatures(int[] temperatures) {
34+
if (temperatures == null || temperatures.length == 0) {
35+
return new int[0];
36+
}
37+
38+
int[] answer = new int[temperatures.length];
39+
Deque<Integer> waitingIndices = new ArrayDeque<>();
40+
41+
for (int i = 0; i < temperatures.length; i++) {
42+
while (!waitingIndices.isEmpty()
43+
&& temperatures[i] > temperatures[waitingIndices.peek()]) {
44+
int waitingIndex = waitingIndices.pop();
45+
answer[waitingIndex] = i - waitingIndex;
46+
}
47+
waitingIndices.push(i);
48+
}
49+
50+
return answer;
51+
}
52+
53+
public static void main(String[] args) {
54+
expect(new int[] {1, 1, 4, 2, 1, 1, 0, 0},
55+
dailyTemperatures(new int[] {73, 74, 75, 71, 69, 72, 76, 73}),
56+
"classic mixed warming and cooling stretch");
57+
58+
expect(new int[] {1, 1, 1, 0},
59+
dailyTemperatures(new int[] {30, 40, 50, 60}),
60+
"strictly increasing -- every day waits one");
61+
62+
expect(new int[] {0, 0, 0, 0},
63+
dailyTemperatures(new int[] {60, 50, 40, 30}),
64+
"strictly decreasing -- no warmer day ever");
65+
66+
expect(new int[] {0, 0, 0, 0},
67+
dailyTemperatures(new int[] {50, 50, 50, 50}),
68+
"ties do not count -- strictly greater required");
69+
70+
expect(new int[] {0},
71+
dailyTemperatures(new int[] {99}),
72+
"single day has no future");
73+
74+
expect(new int[0],
75+
dailyTemperatures(new int[0]),
76+
"empty input returns empty answer");
77+
78+
System.out.println("All DailyTemperatures drill checks passed.");
79+
}
80+
81+
private static void expect(int[] expected, int[] actual, String label) {
82+
if (!Arrays.equals(expected, actual)) {
83+
throw new AssertionError(label
84+
+ " expected " + Arrays.toString(expected)
85+
+ " but got " + Arrays.toString(actual));
86+
}
87+
}
88+
}

interviewDrills/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Short, runnable drills for candidates who want more than a problem list. Each dr
2121
| Drill | Pattern | Why it matters |
2222
| --- | --- | --- |
2323
| [Top K Frequent Words]({% link interviewDrills/top-k-frequent-words.md %}) | Hash map + bounded heap | Common screening shape for search, ranking, logs, and product analytics questions. |
24+
| [Daily Temperatures]({% link interviewDrills/daily-temperatures.md %}) | Monotonic decreasing stack of indices | Standard "next greater element" framing — separates candidates who reach for `O(n^2)` from those who recognize the stack pattern. |
2425

2526
## Practice rule
2627

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
layout: default
3+
title: "Daily Temperatures"
4+
parent: "Interview Drills"
5+
nav_order: 3
6+
---
7+
8+
# Daily Temperatures
9+
10+
**Pattern:** monotonic decreasing stack of indices (next greater element)
11+
**Target time:** 20 minutes coding, 5 minutes explanation, 5 minutes tests
12+
13+
## Problem
14+
15+
Given an integer array `temperatures` where `temperatures[i]` is the
16+
temperature on day `i`, return an array `answer` such that `answer[i]` is
17+
the number of days you must wait after day `i` to get a warmer
18+
temperature. If no future day is warmer, `answer[i] = 0`.
19+
20+
Example:
21+
22+
```text
23+
temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
24+
answer = [ 1, 1, 4, 2, 1, 1, 0, 0]
25+
```
26+
27+
## What to say in the interview
28+
29+
Lead with the trade-off, not the code:
30+
31+
- Brute force is two nested loops, O(n^2). For each day, scan forward for
32+
the first warmer day. This will get you to a working answer but it tells
33+
the interviewer you missed the pattern.
34+
- The pattern is **next greater element**: every position is waiting for
35+
the first strictly greater value to its right. That is a textbook
36+
monotonic-stack problem and runs in O(n).
37+
- Push **indices**, not temperatures. The answer is a *distance*
38+
(`currentIndex - waitingIndex`), so you need the position, not the
39+
value. Look up the temperature through `temperatures[stack.peek()]`.
40+
41+
The invariant: the stack always holds indices whose warmer day has not
42+
been found yet, with their temperatures strictly decreasing from bottom
43+
to top. When today's temperature is strictly greater than the
44+
temperature at the top, today is *the* warmer day for that index and the
45+
answer is fixed forever.
46+
47+
## Common trap
48+
49+
- Storing temperatures on the stack instead of indices. You then cannot
50+
compute the gap and end up smuggling parallel arrays around.
51+
- Using `>=` instead of `>`. Equal temperatures must stay on the stack:
52+
the question asks for *strictly* warmer, so a tie does not resolve
53+
anything.
54+
- Reaching for a heap. A heap is `O(n log n)` and overkill — the
55+
monotonic-stack property gives you each index pushed and popped at
56+
most once, so the total work is `O(n)`.
57+
58+
## Edge cases to test
59+
60+
- empty input returns an empty array;
61+
- single day, like `[99]`, returns `[0]`;
62+
- strictly increasing input, like `[30, 40, 50, 60]`, returns
63+
`[1, 1, 1, 0]`;
64+
- strictly decreasing input, like `[60, 50, 40, 30]`, returns all zeros;
65+
- repeated values, like `[50, 50, 50, 50]`, returns all zeros because
66+
ties do not count.
67+
68+
## Runnable solution
69+
70+
Code: [`DailyTemperatures.java`]({% link interviewDrills/DailyTemperatures.java %})
71+
72+
Run it locally:
73+
74+
```bash
75+
javac interviewDrills/DailyTemperatures.java
76+
java -cp interviewDrills DailyTemperatures
77+
```
78+
79+
Expected output:
80+
81+
```text
82+
All DailyTemperatures drill checks passed.
83+
```

0 commit comments

Comments
 (0)