Next Greater Element
You are given an integer array nums. For each position i, find its next greater element: the first value to the right of index i that is strictly larger than nums[i].
Return an array answer of the same length, where answer[i] is that value, or -1 if nothing to the right of i is larger.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9- Aim for O(n) time: scanning to the right from every index is O(n²).
Examples
Example 1
Input: nums = [2,1,3,5,4] Output: [3,3,5,-1,-1]
1 and 2 both see 3 first. 3 sees 5. Nothing to the right of 5 or 4 is bigger, so both get -1.
Example 2
Input: nums = [5,4,3,2,1] Output: [-1,-1,-1,-1,-1]
Every value is smaller than everything before it, so no element ever finds a bigger one to its right.
Example 3
Input: nums = [3,3,3] Output: [-1,-1,-1]
Equal is not greater: none of the 3s has a strictly larger value after it.
JavaScript you'll use: Stacks, queues and deques Arrays: create, read, update
/**
* @param {number[]} nums
* @return {number[]}
*/
function nextGreater(nums) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.