503. Next Greater Element II
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 66% Topics: Array, Stack, Monotonic Stack
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(n)
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result, stk = [0] * len(nums), []
for i in reversed(xrange(2*len(nums))):
while stk and stk[-1] <= nums[i % len(nums)]:
stk.pop()
result[i % len(nums)] = stk[-1] if stk else -1
stk.append(nums[i % len(nums)])
return result
Solution from kamyu104/LeetCode-Solutions · MIT