Skip to content

Latest commit

 

History

History
54 lines (39 loc) · 1.43 KB

_503. Next Greater Element II.md

File metadata and controls

54 lines (39 loc) · 1.43 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


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 iterate len(nums) times to find the value for each index.

In other languages, this wrapping would have to be added in manually.


Solutions

Python

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