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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit