739. Daily temperatures Leetcode Solution

Daily temperatures Leetcode 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.

jump game leetcode

Daily Temperature Leetcode Solution :

Constraints :

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100

Example 1:

  • Input: temperatures = [30,40,50,60]
  • Output: [1,1,1,0]

Example 2:

  • Input: temperatures = [30,60,90]
  • Output: [1,1,0]

Intuition :

The problem involves finding the number of days one has to wait until a warmer temperature is reached. A stack-based approach can efficiently track the temperatures and their indices while updating the answer.

Approach :
  1. Initialize an empty stack stk to store temperatures and their corresponding indices.
  2. Initialize a vector ans of the same length as the input temperatures to store the number of days to wait for each temperature. Initialize all values in ans to 0.
  3. Iterate through the temperatures vector. For each temperature t at index i:
      While the stack is not empty and the current temperature t is greater than the temperature on top of the stack, pop temperatures from the stack and update the corresponding ans values with the number of days to wait.
      Push the current temperature t and its index i onto the stack.
  4. After processing all temperatures, the ans vector contains the number of days to wait for each temperature.
  5. Return the ans vector as the result.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription