
Next Greater Element II (medium)
Problem Statement
Given a circular integer array nums, return the array containing the next greater number for each element in nums.
A next greater number of a number num is the first greater number than the current number in its traversing-order in the array, which means you could search circularly to find its next greater number. If the next greater element doesn't exist, return -1 for the particular number number.
Examples
-
Example 1:
- Input: nums =
[2, 1, 2, 4, 3] - Expected Output:
[4, 2, 4, -1, 4] - Justification: For
2, the next greater number is4. For1, it's2(the next number in the array). For the second2,4is again the next greater. For4, there's no greater number, hence-1. For3, looping over,4is the next greater number.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 5, 3, 6, 4] - Expected Output:
[5, 6, 6, -1, 5] - Justification: The next greater for
1is5, for5is6, for3is6again, and for6there's no greater number (-1). For4, considering the circular nature,5is the next greater number.
- Input: nums =
-
Example 3:
- Input: nums =
[9, 8, 7, 3, 2, 1, 6] - Expected Output:
[-1, 9, 9, 6, 6, 6, 9] - Justification: For
9, as it's the greatest, no number is greater, so-1. For8and7,9is the next greater number. For3,2, and1, the next greater number is6, considering the circular array. For6,9is the next greater number by looping over.
- Input: nums =
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory