oneby7

Stacks and Queues Monotonic stack

212. Next Greater Element II

Medium

You are given an array of integers nums arranged in a circle: after the last value comes the first one again.

For each position i, walk forward from i around the circle and look at the other values one by one. The next greater element of nums[i] is the first of those values that is larger than nums[i]. An equal value is not larger. The walk stops when it comes back to i, so if no other value is larger, the answer is -1.

Return an array answer of the same length as nums, where answer[i] is the next greater element of nums[i].

Example 1

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

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

Explanation: Nothing beats 8, so its answer is −1. The walk from 2 runs off the end and wraps to the 3 at the start. The walk from 4 passes 1, 2 and 3, which are all smaller, and stops at 8.

Example 2

Input: nums = [7, 7, 2, 7]

Output: [-1,-1,7,-1]

Explanation: An equal value is not larger, so every 7 gets −1. The first value after 2 is a 7, which is larger.

Example 3

Input: nums = [10, 6, 0]

Output: [-1,10,10]

Explanation: The values fall from left to right, so 6 and 0 both have to wrap around to find the 10 at the start.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 6, 1, 5]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.