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 > i
  • nums[j] > nums[i]
  • There exists exactly one index k such that nums[k] > nums[i] and i < 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
Next Greater Element IV INPUT nums array: 1 i=0 2 i=1 4 i=2 3 i=3 Find SECOND greater element for each nums[i] For nums[0]=1: 1st greater: 2 2nd greater: 4 1st 2nd ALGORITHM STEPS 1 Use Two Stacks stack1: waiting for 1st greater stack2: waiting for 2nd greater 2 Process Each Element Pop from stack2 if current is greater (found 2nd) 3 Transfer Elements Move from stack1 to stack2 when 1st greater found 4 Push Current Index Add current to stack1 for future processing Stack State Example: stack1 stack2 FINAL RESULT answer array: 4 i=0 3 i=1 -1 i=2 -1 i=3 Breakdown: nums[0]=1: 2nd greater = 4 OK nums[1]=2: 2nd greater = 3 OK nums[2]=4: no 2nd greater -1 nums[3]=3: no 2nd greater -1 Output: [4, 3, -1, -1] Time: O(n) | Space: O(n) Key Insight: Use two monotonic stacks to track elements waiting for their 1st and 2nd greater elements. When an element finds its 1st greater, move it to stack2. When it finds its 2nd greater in stack2, record the answer. This ensures O(n) time complexity as each element is pushed/popped at most twice. TutorialsPoint - Next Greater Element IV | Optimal Solution (Two Monotonic Stacks)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
24.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen