Example 1
Input
nums = [1, 2, 1]
Output
[2, -1, 2]
For the first 1 the next greater is 2. For the middle 2 there is no greater element in the circular array, so -1. For the last 1 the next greater (wrapping) is 2.
Full lesson preview
Given a circular array of integers, find the next greater element for every entry. Use a monotonic stack and a two-pass approach to achieve O(n) time.
Problem statement
Task
Examples
Input
nums = [1, 2, 1]
Output
[2, -1, 2]
For the first 1 the next greater is 2. For the middle 2 there is no greater element in the circular array, so -1. For the last 1 the next greater (wrapping) is 2.
Input format
Output format
Constraints
Samples
Input
[5, 4, 3, 2, 1]
Output
[-1, 5, 5, 5, 5]
5 has no greater element. The others find 5 by wrapping around.