Table of contents
1.
Introduction
2.
Problem Statement
3.
Naive Approach
4.
Stack Approach
4.1.
Algorithm
4.2.
Code in Java
4.3.
Complexity Analysis
5.
Frequently Asked Questions
5.1.
What is a monotonic stack?
5.2.
What does pop() do?
5.3.
What does push() do?
5.4.
What happens if there isn’t any day where a warmer temperature is possible in daily temperature problems?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Daily Temperatures

Author Reet Maggo
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?
Stacks

Introduction

Array is a popular data structure and one of the first data structures that are learned while beginning to learn data structures or any programming language. A wide number of questions are also asked on arrays in technical interviews of top tech companies. A mastery over arrays could help open doors to a lot of new ideas for approaching a programming problem and solving it. In this article, we are going to take a look at one such problem.

Problem Statement

In a given integer array of everyday temperatures, the task is to find the number of days remaining for the next day with a warmer temperature. If there is no day in the future for which warmer temperature is possible, print -1.

This blog will explore the various approaches to solve such problems and discuss each approach's time and space complexities.


Examples

Eg. 1- Input: temperatures = [30,60,90]

Output: 

 

1,1,-1

 

After 30, the following warmer temperature is 60, at a distance of 1 

After 60, the next warmer temperature is 90, at a distance of 1

After 90, there is no warmer temperature further

 

Eg. 2- Input: arr[] = {78, 75, 74, 72} 

Output:

 

-1, -1, -1, -1

 

The given array is in descending order, so:

After 78, there is no warmer temperature further

After 75, there is no warmer temperature further

After 74, there is no warmer temperature further

After 72, there is no warmer temperature further
 

Eg. 3- Input: arr[]:

input array

Output: 

6, 2, 1, 3, 1, 1, -1, -1

After 75, the following warmer temperature is 76, at a distance of 6 

After 73, the next warmer temperature is 74, at a distance of 2

After 71, the next warmer temperature is 74, at a distance of 1

After 74, the next warmer temperature is 76, at a distance of 3

After 69, the following warmer temperature is 72, at a distance of 1 

After 72, the next warmer temperature is 76, at a distance of 1 

After 76, there is no warmer temperature further

After 73, there is no warmer temperature further

Naive Approach

In this approach, we will iterate for every possible pair in the temperature array and check the next warmer temperature for every current element.

Time Complexity: O(n²)

Since we will have a nested loop that checks every pair of temperatures, the running time will increase non-linearly with the input length. Considering there will be a loop within a loop where one loop takes O(n) time, the time complexity will become O(n)*O(n) = O(n^2).

Auxiliary Space: O(1)

The space required for the data in this array will be constant, i.e., it is not growing with the array data. Therefore, the space complexity will be O(1).

Stack Approach

We can use a monotonic (sorted) decreasing stack to hold temperatures in decreasing order. The problem is primarily about finding the number of days till the next warmer temperature. Hence, we will store the indices of the days instead of temperatures and use the temperature [current day] to find the current day's temperature.

Algorithm

  • In the given array, we will use the current index to the daily temperatures.
  • The current index will be pushed to the stack if the stack is empty.
  • However, if the stack isn’t empty:
    • If the current temperature is lesser than the one at the top of the stack, push the current index.
    • If the current temperature is greater than the one at the top of the stack, update the number of days to wait by making the current index the index at the top.
    • When the number of days to wait is updated in the output list, pop the stack.
  • Repeat the above steps for all the indices in the stack that are lesser than the temperature at the current index.

Code in Java

import java.util.*;
import java.lang.*;
 
class dailyTemperatures
{
    static void dailyTemp(int[] temp)
    {
        int n = temp.length;
 
        // for storing the answer
        int[] daysToWait = new int[n];
        Arrays.fill(daysToWait, -1);
    
        Stack<Integer> s = new Stack<>();
    
        // Traversing all temperatures in the array
        for(int i = 0; i < n; i++)
        {
        
            /* checking if current index is warmer temp than previous
            indexes */
            while (!s.isEmpty() && temp[s.peek()] < temp[i])
            {
                daysToWait[s.peek()] = i - s.peek();
            
                // to pop the element
                s.pop();
            }
        
            // to push the current index
            s.push(i);
        }
 
        // days to wait will be printed
        for(int i = 0; i < n; i++)
        {
            System.out.print(daysToWait[i] + " ");
        }
    }
    
    // calling function
    public static void main (String[] args)
    {
        int[] arr = { 75, 73, 71, 74, 69, 72, 76, 73 };
        dailyTemp(arr);
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

6, 2, 1, 3, 1, 1, -1, -1

Complexity Analysis

Time and space complexity: Given N is the length of the temperatures array,

Time Complexity: O(N) 

Every individual element is added to the stack only once, limiting the stack to N pops. Every element in the while loop will be pushed and popped once at the most, meaning the loop won’t iterate more than N times. Hence, this will have a time complexity of O(N).

Auxiliary Space: O(N)

For non-increasing input, no element will be popped, and the stack would thus grow to the size of N elements.

Frequently Asked Questions

What is a monotonic stack?

A monotonic stack is a kind of stack data structure itself, but as the name suggests, it is not random. A monotonic stack is sorted either in increasing or decreasing order while containing all other features of a normal stack.

What does pop() do?

The pop() function is a method that can be used to remove the last element of the given array and returns that element.

What does push() do?

The push() is a method that can add one or several elements at the end of an array and return the new array’s length.

What happens if there isn’t any day where a warmer temperature is possible in daily temperature problems?

In daily temperature problems, when there is no possible day with a warmer temperature, then programs are usually written to either print 0 or -1.

Conclusion

In this article, we learned how to find the remaining days for the next day having a higher temperature than the current one. We understood various approaches, their time and space complexity, along their code snippets.

Recommended Readings:


Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Check out this problem - Search In Rotated Sorted Array

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Cheers!

Live masterclass