← Home

739. Daily Temperatures

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
739

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 739. Daily Temperatures, the solution in this repository is mainly a stack solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 2 for loop, O(n^2)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dailyTemperatures, temp2ix.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//2 for loop, O(n^2)
03class Solution {
04public:
05    vector<int> dailyTemperatures(vector<int>& T) {
06        vector<int> ans;
07        for(int i = 0; i < T.size(); i++){
08            bool found = false;
09            for(int j = i+1; j < T.size(); j++){
10                if(T[j] > T[i]){
11                    ans.push_back(j-i); 
12                    found = true;
13                    break;
14                }
15            }
16            if(!found) ans.push_back(0);
17        }
18        return ans;
19    }
20};
21
22//Approach #1: Next Array(use a map)
23//Runtime: 204 ms, faster than 32.99% of C++ online submissions for Daily Temperatures.
24//Memory Usage: 14.1 MB, less than 100.00% of C++ online submissions for Daily Temperatures.
25//N: size of T, W: range of T's value, time:O(NW), space: O(N+W)
26class Solution {
27public:
28    vector<int> dailyTemperatures(vector<int>& T) {
29        vector<int> ans(T.size());
30        vector<int> temp2ix(101, INT_MAX); //the maximum value of temperature is 100
31        
32        for(int i = T.size()-1; i >= 0; i--){
33            int warmer_index = INT_MAX;
34            for(int t = T[i] + 1; t <= 100; t++){
35                warmer_index = min(warmer_index, temp2ix[t]);
36            }
37            if(warmer_index < INT_MAX)
38                ans[i] = warmer_index - i;
39            temp2ix[T[i]] = i;
40        }
41        
42        return ans;
43    }
44};
45
46//Approach #2: Stack
47//Runtime: 188 ms, faster than 88.60% of C++ online submissions for Daily Temperatures.
48//Memory Usage: 13.9 MB, less than 100.00% of C++ online submissions for Daily Temperatures.
49
50class Solution {
51public:
52    vector<int> dailyTemperatures(vector<int>& T) {
53        vector<int> ans(T.size());
54        stack<int> stk;
55        
56        for(int i = T.size()-1; i >= 0; i--){
57            //pop all values < current value
58            while(!stk.empty() && T[stk.top()] <= T[i]){
59                stk.pop();
60            }
61            ans[i] = stk.empty()?0:stk.top()-i;
62            stk.push(i);
63        }
64        return ans;
65    }
66};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.