Next Greater Element II

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given a circular integer array nums, return the next greater number for every element in the array.

The next greater number of a number x is the first number that is greater than x when traversing the array circularly. If no greater number exists, return -1 for that element.

Examples

Example 1:

Input: nums = [1,2,1]

Output: [2,-1,2]

Explanation: The next greater number for 1 (index 0) is 2. There is no greater number for 2, so it returns -1. The next greater number for 1 (index 2) wraps around circularly to 2 at index 1.

Example 2:

Input: nums = [1,2,3,4,3]

Output: [2,3,4,-1,4]

Explanation: For 4 there is no greater element even after wrapping around, so it returns -1. For 3 (index 4), wrapping around finds 4 at index 3.

Example 3:

Input: nums = [5,4,3,2,1]

Output: [-1,5,5,5,5]

Explanation: 5 is the largest so its next greater is -1. All other elements find 5 by wrapping around.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
Source: Monotonic Stack pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle