Next Greater Element in a Circular List
Given a circular list of integers nums, find the next greater element for every value.
The next greater element of nums[i] is the first value greater than nums[i] encountered while moving forward. After the last element, the search continues from the first element.
If no greater element exists, use -1 for that position.
Method Signature
List<Integer> nextGreaterElements(List<Integer> nums)
nums is the circular list of integers.
- Return a list where the value at index
i is the next greater element of nums[i], or -1 when none exists.
- The returned values must follow the original index order.
Constraints
1 ≤ nums.size() ≤ 10,000
-1,000,000,000 ≤ nums.get(i) ≤ 1,000,000,000
Examples
Example 1
nextGreaterElements(nums = List.of(3, 1, 2))
Output: [-1, 2, 3]
No value is greater than 3. The next greater value after 1 is 2. For 2, the circular search reaches 3.
Example 2
nextGreaterElements(nums = List.of(5, 4, 3, 2, 1))
Output: [-1, 5, 5, 5, 5]
The first element has no greater value. Every other element reaches 5 after continuing circularly.
Example 3
nextGreaterElements(nums = List.of(7, 7, 7))
Output: [-1, -1, -1]
Equal values are not greater, so no element has a next greater value.