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: Find Second Greater1243i=0i=1i=2i=3For each element, find the second element to the right that is greater1 → 2,4,3 → 42 → 4,3 → 34 → 3 → -13 → none → -143-1-1Result: [4, 3, -1, -1]
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
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