Next Greater Element IV Problem
#2454
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2454.
You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > inums[j] > nums[i]- There exists exactly one index
ksuch thatnums[k] > nums[i]andi < k < j.
If there is no such nums[j], the second greater integer is considered to be -1.
- For example, in the array
[1, 2, 4, 3], the second greater integer of1is4,2is3, and that of3and4is-1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Example 1:
Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].
Example 2:
Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Two Monotonic Stacks
Keep two stacks of indexes. s1 holds elements still waiting for their first greater element, s2 holds elements that have found one and wait for a second.
For each new value x:
- Pop every element of s2 smaller than x: x is their second greater element.
- Pop every element of s1 smaller than x (they have now met their first greater element) and move them onto s2, keeping their relative order so s2 stays monotonic.
- Push the current index onto s1.
Elements left on the stacks at the end have answer -1.
Complexity: O(n) time and O(n) space.
class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [-1] * n
s1, s2 = [], []
for i, x in enumerate(nums):
while s2 and nums[s2[-1]] < x:
ans[s2.pop()] = x
t = []
while s1 and nums[s1[-1]] < x:
t.append(s1.pop())
s2.extend(reversed(t))
s1.append(i)
return ans