Next Greater Element IV - Problem
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 of 1 is 4, 2 is 3, and that of 3 and 4 is -1.
Return an integer array answer, where answer[i] is the second greater integer of nums[i].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,4,3]
›
Output:
[4,3,-1,-1]
💡 Note:
For 1: greater elements are 2,4,3 → second greater is 4. For 2: greater elements are 4,3 → second greater is 3. For 4 and 3: no second greater element exists.
Example 2 — All Decreasing
$
Input:
nums = [5,4,3,2,1]
›
Output:
[-1,-1,-1,-1,-1]
💡 Note:
In a decreasing array, no element has a greater element to its right, so all results are -1.
Example 3 — All Increasing
$
Input:
nums = [1,2,3,4,5]
›
Output:
[3,4,5,-1,-1]
💡 Note:
For 1: greater are 2,3,4,5 → second is 3. For 2: greater are 3,4,5 → second is 4. For 3: greater are 4,5 → second is 5.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array [1,2,4,3] with indices
2
Find Second Greater
For each element, find the second element greater than it
3
Result
Output [4,3,-1,-1] showing second greater for each
Key Takeaway
🎯 Key Insight: Use two monotonic stacks to track first and second greater elements efficiently in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code