JavaScript O(n): 'Think-How-Your-Brain-Thinks' Solution. With comments.
I looked at other solutions where they had a for loop going over double the size of the input array and doing \'%\' (modulo) and stuff like that. While that is 
I looked at other solutions where they had a for loop going over double the size of the input array and doing \'%\' (modulo) and stuff like that. While that is a smart way to do it, I think the following approach helped me think in a better/cleaner way.\n\nNOTE: We push the indexes of the elements in the stack and not the elements themselves. Just read the solution and try to go over this case (nums = [1,4,2,1,2]), you will get what it\'s doing.\n\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar nextGreaterElements = function(nums) {\n    const ret = [];\n    const stack = [];\n\n\t//paranoid base case.\n    if (!nums || nums.length < 1) return ret;\n\t\n\t//normal case: while iterating over the array if we find an element which is  bigger\n\t//than one in the stack, set ret[`smaller element from stack`] to the current\n\t//larger element found.\n    for (let i = 0; i < nums.length; i++) {\n        while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {\n            const smallerEleIndexFromStack = stack.pop();\n            ret[smallerEleIndexFromStack] = nums[i];\n        }\n        stack.push(i);\n    }\n\n\t//Now, we again begin from the start of nums and deal with elements\n\t//for which we couldn\'t find a \'next bigger element\' in the previous for loop\n\t//Example: nums = [1,4,2,1,2]. After the first loop, the stack would still hold the\n\t//indexes 1, 2 and 4 since we couldn\'t find next elements bigger than nums[1],\n\t//nums[2] and nums[4].\n    for (let i = 0; i < nums.length; i++) {\n        while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[i]) {\n            const smallerEleIndexFromStack = stack.pop();\n            ret[smallerEleIndexFromStack] = nums[i];\n        }\n    }\n\n\t//Finally, still there would be some elements for which there was no \'next greater element\'\n\t//In the case of nums = [1,4,2,1,2], 4 would be such an element. So we just go over the\n\t//remaining elements in the stack and assign -1 to them in ret array.\n    const remaining = stack.length;\n    for (let i = 0; i < remaining; i++) {\n        ret[stack.pop()] = -1;\n    }\n\n    return ret;\n};\n```\n\nPlease let me know if any part of the solution is unclear/confusing.
[]