Back to course home
0% completed
Vote For New Content
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
,4
is again the next greater. For4
, there's no greater number, hence-1
. For3
, looping over,4
is 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
1
is5
, for5
is6
, for3
is6
again, and for6
there's no greater number (-1
). For4
, considering the circular nature,5
is 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
. For8
and7
,9
is the next greater number. For3
,2
, and1
, the next greater number is6
, considering the circular array. For6
,9
is the next greater number by looping over.
- Input: nums =
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible