Python Stack 98.78% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack
Basic Idea:\n\n1. Well loop once, in that way we get the Next Greater Number of a normal array.\n2. Well Loop second time, then we will get the Next Greater Num
**Basic Idea:**\n\n1. We`ll loop once, in that way we get the Next Greater Number of a normal array.\n2. We`ll Loop second time, then we will get the Next Greater Number of a circular array.\n\n**Optimised solution :**\n```\nclass Solution:\n    def nextGreaterElements(self, nums: List[int]) -> List[int]:\n        stack, res = [], [-1] * len(nums) # taking an empty stack for storing index, a list with the lenght same as of nums so that we wont add unnecessary elements.\n        # [-1] * len(nums) = this will produce a list with len of nums and all elems will be -1.\n        for i in list(range(len(nums))) * 2: # see explanation below.\n            while stack and (nums[stack[-1]] < nums[i]): # stack is not empty and nums previous elem is less then current, i.e 1<2. \n                res[stack.pop()] = nums[i] # then we`ll pop the index in stack and in the res on the same index will add the current num. \n            stack.append(i) # if stack is empty then we`ll add the index of num in it for comparision to the next element in the provided list. \n        return res # returing the next greater number for every element in nums.\n```\n\n >**for i in list(range(len(nums))) * 2:**\n > As we know the given array is circular integer array, so we have to run the for loop twice so that we could compare last elments of the list to the first elements. \n > In python 3, just `for i in range(len(nums)) * 2` will thrown exception `TypeError: unsupported operand type(s) for *: \'range\' and \'int\'`, however if we put range inside it`ll work fine. Using list() is a little hack to make it work. \n\n**Expantion of the above solution :**\n```python\nstack, r = [], [-1] * len(nums)\n        for i in range(len(nums)):\n            while stack and (nums[stack[-1]] < nums[i]):\n                r[stack.pop()] = nums[i]\n            stack.append(i)\n        for i in range(len(nums)):\n            while stack and (nums[stack[-1]] < nums[i]):\n                r[stack.pop()] = nums[i]\n            if stack == []:\n                break\n        return r\n```\n\n***Found helpful, Do upvote !!***
['Stack', 'Monotonic Stack', 'Python', 'Python3']