Next Greater Element II

Medium#503

The array is a circle: after the last number comes the first one again. For every number, find the first greater number going forward around the circle; if there is none, the answer is -1. Our example: [6, 2, 5, 1, 3] gives [-1, 5, 6, 3, 6].

input
nums: integers on a circle: after the last one comes the first one again. Numbers may repeat.
returns
For each number, the first number greater than it going forward around the circle, or -1 if there is none. An equal number is not greater.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −10⁹ ≤ nums[i] ≤ 10⁹
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number[]}
 */
function nextGreaterElements(nums) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more monotonic stack problems

Pattern “Monotonic stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.