Given an array of integers
Output: [1,1,4,2,1,1,0,0]
Output: [1,1,1,0]
Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105 30 <= temperatures[i] <= 100
Contents
Solution 1 - Using stack, construct a monotonically decreasing stack
In this approach, we are going to build a monotonically decreasing stack, meaning that elements in the stack should be in a decreasing order, when we see a number higher than the top of the stack, then we delete elements from stack to ensure that the stack is still monotonically decreasing order.
Implementation steps:
-
First, we will create two variables
result an integer array, that we are going to return as answer, andstack aStack that we will use to store temparatures in monotonically decreasing order. -
Next, loop through input array
temperatures and add the current element's index into thestack , but before adding the current index into thestack we need to make sure that it it monotonically decreasing order. So, what we will do is check the top of the stack element and see if its corresponding value is smaller than current element, then we will remove that index fromb-v . While doing this check, we will also fillresult array, we will update stack's top element index inresult withi - stack's top , this means that the current element next greater element, and it is ati- index stored in stack distance.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n).
Above implementations source code can be found at