Skip to content

Commit

Permalink
Next Greater Element II
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-sukhoverkhov committed Aug 21, 2024
1 parent e59ca17 commit 487e132
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions python/leetcode/Next Greater Element II.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from typing import List


class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:

ln = len(nums)
s = []
res = [0] * ln
for i in range(ln*2-1, -1, -1):
idx = i % ln

while s and s[-1] <= nums[idx]:
s.pop()

if not s:
res[idx] = -1
else:
res[idx] = s[-1]

s.append(nums[idx])

return res


if __name__ == "__main__":
obj = Solution()

nums = [8, 7, 6, 5]
assert obj.nextGreaterElements(nums) == [-1, 8, 8, 8]

nums = [1, 2, 1]
assert obj.nextGreaterElements(nums) == [2, -1, 2]

nums = [1, 2, 3, 4, 3]
assert obj.nextGreaterElements(nums) == [2, 3, 4, -1, 4]

0 comments on commit 487e132

Please sign in to comment.