AlgoLounge

Next Greater Element

medium

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Examples

Example 1

Input:  nums = [1, 2, 1]
Output: [2, -1, 2]

The next greater number for 1 is 2. The number 2 has no greater number. The next greater of the last 1 is 2 (wrapping around).

Example 2

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

Example 3

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

Every element except 5 wraps around and finds 5 as the next greater.

Constraints

  • 1 <= nums.length <= 10000
  • -10^9 <= nums[i] <= 10^9
TypeScript
Loading editor…
List of test cases (10)
Case 1
nums = [1,2,1]
Case 2
nums = [1,2,3,4,3]
Case 3
nums = [5,4,3,2,1]
Case 4
nums = [1,1,1,1]
Case 5
nums = [7]
Case 6
nums = [3,8,4,1,2]
Case 7
nums = [100,1,11,1,120,111,123,1,-1,-100]
Case 8
nums = [2,3,1]
Case 9
nums = [1,5,3,6,8]
Case 10
nums = [9,8,7,3,2,1,6]