Next Greater Element II Problem
Description
LeetCode Problem 503.
Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.
Example 1:
Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
Example 2:
Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]
Constraints:
- 1 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
Solution
Approach: Monotonic Stack over Two Passes
Searching forward from each element is O(n2). A stack finds every next greater number in linear time, and the circular part is handled by walking the array twice.
Keep a stack of indices whose next greater number has not been found yet. Their values decrease from bottom to top, since a smaller value below a larger one would already have been popped.
- Loop
stepfrom0to2n - 1and look ati = step % n. - While the value at the top of the stack is smaller than
nums[i], pop that index and set its answer tonums[i]. - Push
ionly during the first pass (step < n). In the second pass the elements are there only to serve as answers for the indices still waiting. - Indices that are never popped keep the answer
-1: nothing in the whole circle is greater.
The second pass is what makes it circular. For nums = [1,2,1], the last 1 is still waiting after the first pass. In the second pass it meets the 2 at index 1 again and gets its answer 2. Two passes are enough because every other element is reached within n - 1 steps.
The stack stores indices, not values, because nums can contain duplicates and the answer is written by position. Use a strict < so equal numbers do not count as greater.
Complexity: O(n) time and O(n) space, where n is the length of nums. Each index is pushed and popped at most once.
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [-1] * n
stack = [] # indices still waiting for a greater number; their values decrease from bottom to top
# Walk the array twice, so the numbers at the start can serve as next greater numbers for those at the end.
for step in range(2 * n):
i = step % n
while stack and nums[stack[-1]] < nums[i]:
answer[stack.pop()] = nums[i]
if step < n: # each index only needs to wait once
stack.append(i)
return answer
Now write it from memory
Close the write-up and solve it yourself against the tests.