Problem Description
Write a function that calculates the number of days between the current day and the next day with a higher temperature.
Input
An array of non-negative integers. Each number is the temperature on the corresponding day.
Output
An array of non-negative integers. Each number is the number of days from the i-th day until a day with a higher temperature.
Constraints
- The number of days (input array length) is in the range from 1 to 100000
- The temperature for each day is in the range from 30 to 100
Examples
Input: [73,74,75,71,69,72,76,73]
Answer: [1,1,4,2,1,1,0,0]
Stack approach
The problem can be solved in linear time using a stack.
The solution is very similar to the ones for asteroid collision and valid parentheses.
We need a result array, a stack (which can be implemented on top of an array), and a loop over the elements of the input array:
- Fill the result array with zeros (its size equals the size of the input array)
- If the stack is not empty, run an inner loop popping elements (indices) from the stack (for convenience, let's call the index popped from the top of the stack
iand the index of the current dayj):- If the temperature on day
jis lower than on dayi, pushiback onto the stack, pushjon top of it, exit the inner loop and move on to the next day. - If the temperature on day
jis higher, set thei-th element of the result array toj - i(jis the current day number andiis the day number from the stack, so their difference is exactly the number of days between them). Pop the next element from the stack.
- If the temperature on day
- If the stack is empty, push the index
jonto the stack.
export const dailyTemperatures = (temperatures: number[]): number[] => {
const stack: number[] = [];
const res: number[] = new Array(temperatures.length).fill(0);
temperatures.forEach((dailyTemp, j) => {
while (stack.length > 0 && dailyTemp > temperatures[stack[stack.length - 1]]) {
const i = stack[stack.length - 1];
stack.pop();
res[i] = j - i;
}
stack.push(j);
});
return res;
};Complexity Analysis
Time Complexity
O(n), where n is the number of days.
In the worst case we push n - 1 elements onto the stack and then pop all of them. So the maximum number of operations is 2n, which is equivalent to O(n) in terms of asymptotic analysis.
Space Complexity
O(n), since we create a stack and a result array to store the data.