JavaScript Commented in Detail
Time complexity: O(n)  \n- Space complexity: O(n)\n\n# Code\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar secondGreaterElement = function(n
- Time complexity: $$O(n)$$  \n- Space complexity: $$O(n)$$\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar secondGreaterElement = function(nums) {\n    const n = nums.length;\n    // Create an array to store the results.\n    const ans = new Array(n).fill(-1);\n    // Create a decreasing stack to store the indices that met the first greater num.\n    const pre = [];\n    // Create a decreasing stack to store the indices.\n    const cur = [];\n\n    for (let i = 0; i < n; i++) {\n        const num = nums[i];\n        // While there are indices in the previous stack that meet the second greater num.\n        while (pre.length > 0 && nums[pre[pre.length - 1]] < num) {\n            // Update the results.\n            ans[pre.pop()] = num;\n        }\n        // Push indices that meet the first greater num from `cur` to `pre`.\n        // Create a temp array to make indices in `pre` increasing.\n        const tmp = [];\n        while (cur.length > 0 && nums[cur[cur.length - 1]] < num) {\n            tmp.push(cur.pop());\n        }\n        // While there are indices in `tmp`, push them to `pre`.\n        while (tmp.length > 0) {\n            pre.push(tmp.pop());\n        }\n        // Push the current index to `cur`.\n        cur.push(i);\n    }\n\n    return ans;\n}\n```
['Array', 'Binary Search', 'Stack', 'Monotonic Stack', 'JavaScript']