AlgoMaster Logo

Daily Temperatures

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

We can start with a straightforward approach by simply checking each temperature against all the following temperatures to see when a warmer day occurs. This involves traversing every pair of days, which can be inefficient.

Steps:

  1. For each day in the list of temperatures, we need to find the number of days until a warmer temperature appears.
  2. We'll make a nested iteration, fixing one element from the start and iterating through the following temperatures to find the first one greater than our fixed element.
  3. If we find such a day, we calculate how many days ahead it is and store that in our result list.

Code:

2. Using a Stack

Intuition:

By utilizing a stack, we can reduce the repeated comparisons to gain an optimal solution. We will use a stack to keep track of indices of the temperatures that need to find a warmer temperature.

Steps:

  1. We will maintain a stack to store indices of the temperatures.
  2. As we iterate over each day's temperature, we compare it with the temperatures corresponding to the indices in our stack.
  3. If the current day's temperature is warmer than the temperature at the index stored at the top of the stack, we pop the index from the stack and update our result with the number of days we've moved forward to find a warmer temperature.
  4. We push the current index onto the stack if we don't find a warmer temperature.
  5. This way, each temperature is processed once, ensuring efficiency.

Code: