All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 05, 2024
Last updated : July 05, 2024
Related Topics : Array, Stack, Monotonic Stack
Acceptance Rate : 65.19 %
Since
Python
supports array index calls overflowing to the end, we can start from the max value present, add it to a running stack of the next max value in descending order, and iteratelen(nums)
times to find the value for each index.In other languages, this wrapping would have to be added in manually.
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
maxIndx = max(list(range(len(nums))), key=lambda x: nums[x])
stk = [nums[maxIndx]]
output = [0] * len(nums)
for i in range(maxIndx - 1, maxIndx - 1 - len(nums), -1) :
while stk and stk[-1] <= nums[i] :
stk.pop()
if stk :
output[i] = stk[-1]
else :
output[i] = -1
stk.append(nums[i])
return output