1. Nested Loops Search
Intuition
For each day i, scan forward to find the first index j > i where temperatures[j] > temperatures[i] and record j - i.
Algorithm
- Step 1: Initialize an answer array
ansof sizeNfilled with 0. - Step 2: Loop
ifrom 0 toN - 1. - Step 3: Inside, loop
jfromi + 1toN - 1. - Step 4: If
temperatures[j] > temperatures[i], setans[i] = j - iand break inner loop. - Step 5: Return
ans.
#include <iostream>#include <vector> class Solution {public: std::vector<int> dailyTemperatures(std::vector<int>& temperatures) { int n = temperatures.size(); std::vector<int> ans(n, 0); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { ans[i] = j - i; break; } } } return ans; }}; int main() { Solution solver; std::vector<int> temps = {73, 74, 75, 71, 69, 72, 76, 73}; std::vector<int> ans = solver.dailyTemperatures(temps); std::cout << "Output: ["; for (size_t i = 0; i < ans.size(); i++) { std::cout << ans[i] << (i + 1 < ans.size() ? ", " : ""); } std::cout << "]" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— For each day i, we check all subsequent days j > i in the worst case (e.g. strictly decreasing temperatures), taking O(N2) total comparisons. - Space complexity:
O(1)— O(1) extra auxiliary space beyond the output array.
Why Brute Force Doesn't Scale:
A strictly decreasing sequence of 100,000 elements requires ~5 * 109 comparisons.
At N = 100,000, Monotonic Stack finishes in ~10ms compared to several seconds for O(N2).