Given an array of non-negative integers, your task is to find the second greater element for each number in the array.

The second greater element of nums[i] is the first element to the right that is greater than nums[i], but with exactly one greater element between them.

More formally, nums[j] is the second greater element of nums[i] if:

  • j > i (appears after the current element)
  • nums[j] > nums[i] (is greater than current element)
  • There exists exactly one index k where i < k < j and nums[k] > nums[i]

If no such element exists, return -1 for that position.

Example: In array [1, 2, 4, 3], the second greater element of 1 is 4 (with 2 as the first greater), and for 2 it's 3 (with 4 as the first greater).

Input & Output

example_1.py — Basic case
$ Input: [1, 2, 4, 3]
Output: [4, 3, -1, -1]
💡 Note: For 1: first greater is 2, second greater is 4. For 2: first greater is 4, second greater is 3. For 4 and 3: no second greater elements exist.
example_2.py — Increasing sequence
$ Input: [2, 4, 0, 9, 6]
Output: [9, 6, 9, -1, -1]
💡 Note: For 2: first greater is 4, second greater is 9. For 4: first greater is 9, second greater is 6. For 0: first greater is 2, second greater is 9.
example_3.py — Edge case with duplicates
$ Input: [3, 3]
Output: [-1, -1]
💡 Note: No element has a second greater element since we need strictly greater elements and there are only duplicates.

Visualization

Tap to expand
Mountain Peak Finder Visualization1243First Peak Seekers43Waiting for 1st greaterSecond Peak Seekers12Waiting for 2nd greaterResults Found1 → 4 ✓2 → 3 ✓4 → -13 → -1Found!
Understanding the Visualization
1
Arrival of New Hiker
A new hiker (element) arrives at the trail
2
Check Second Peak Seekers
Check if this hiker's position can serve as the second peak for anyone in the second group
3
Promote First Peak Finders
Move hikers from first group to second group if current position is their first peak
4
Add to First Group
Add the new hiker to the first group to search for their first peak
Key Takeaway
🎯 Key Insight: By managing two separate groups (stacks) of elements based on their progress toward finding greater elements, we can efficiently solve the problem in a single pass with optimal time complexity.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through array, each element is pushed and popped from stacks at most once

n
2n
Linear Growth
Space Complexity
O(n)

Space for result array and two monotonic stacks, each can hold at most n elements

n
2n
Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] ≤ 109
  • Follow up: Could you find an O(n) time solution?
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
47.2K Views
High Frequency
~25 min Avg. Time
1.7K 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