What is Next Greater Element
For each value, the next greater element is the first value to its right that is strictly larger. If none exists, the answer is -1.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is pushed and popped at most once. |
| Space | O(n) | The stack and the answer row. |
Implementation
def solve(self, nums):
n = len(nums)
ans = [-1]*n
st = []
for i, val in enumerate(nums):
while st and nums[st[-1]] < val:
ans[st.pop()] = val
st.append(i)
return ans