MEDIUM NC#25 Stack
739. Daily Temperatures
๐ Problem
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use stack to store indices of days with unresolved warmer temperature
- โ For each day, pop all days with lower temperatures
- โ The difference in indices is the days waited
- โ Time: O(n), Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse stack to store indices of days with unresolved warmer temperature
- โขFor each day, pop all days with lower temperatures
- โขThe difference in indices is the days waited
Common Pitfalls
- โขTime: O(n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
dailyTemperatures([73,74,75,71,69,72,76,73]); Expected:
[1, 1, 4, 2, 1, 1, 0, 0] Test Case 2
Not run Input:
dailyTemperatures([30,40,50,60]); Expected:
[1, 1, 1, 0] Test Case 3
Not run Input:
dailyTemperatures([30,60,90]); Expected:
[1, 1, 0] ๐ Code Editor
๐ค Output