Explanation of the high rated solution
Try to explain Ya Chen Chang\'s solution. It\'s concise and elegant but I could get the main idea at the first glance. I hope this could help to make it clear t
Try to explain [Ya Chen Chang](https://leetcode.com/problems/next-greater-element-ii/discuss/145374/Python-beats-100http://)\'s solution. It\'s concise and elegant but I could get the main idea at the first glance. I hope this could help to make it clear that how it works.\n\nThe code:\n```\nclass Solution(object):\n    def nextGreaterElements(self, nums):\n        n = len(nums)\n        ret = [-1] * n\n        stack = nums[::-1]\n        for i in range(n - 1, -1, -1):\n            while stack and stack[-1] <= nums[i]:\n                stack.pop()\n            if stack:\n                ret[i] = stack[-1]\n            stack.append(nums[i])\n        return ret\n```\n\nFirst ignore that it\'s a circular array. Then the code is almost the same except that stack should be initisalized as an emplty stack:\n```\nclass Solution(object):\n    def nextGreaterElements(self, nums):\n        n = len(nums)\n        ret = [-1] * n\n        stack1 = []\n        # stack = nums[::-1]\n        for i in range(n - 1, -1, -1):\n            while stack1 and stack1[-1] <= nums[i]:\n                stack1.pop()\n            if stack1:\n                ret[i] = stack1[-1]\n            stack1.append(nums[i])\n        return ret\n```\nThen consider the circular condition. When stack1 is empty, we still could try to find the next greater element from the begining of the array. The code is like this:\n```\nclass Solution(object):\n    def nextGreaterElements(self, nums):       \n        n = len(nums)\n        ret = [-1] * n\n        stack1 = []\n        stack2 = nums[::-1]\n        for i in range(n - 1, -1, -1):\n            while stack1 and stack1[-1] <= nums[i]:\n                stack1.pop()\n            if stack1:\n                ret[i] = stack1[-1]\n            else:\n                while stack2 and stack2[-1] <= nums[i]:\n                    stack2.pop()\n                if stack2:\n                    ret[i] = stack2[-1]                \n            stack1.append(nums[i])\n        return ret\n```\nBut there\'s no need to distinguish stack1 and stack2, so the original code follows.
[]