BackmediumStack

Consecutive Next Greater Elements Solution

Problem Statement

Given an array of integers, find the next greater element for each element in the array. The next greater element is the first element to the right of the current element that is greater than the current element. If no such element exists, return -1.

Example 1
Input
[4, 5, 2, 10, 8]
Output
[5, 10, 10, -1, -1]

Explanation: For the first element 4, the next greater element is 5. For the second element 5, the next greater element is 10. For the third element 2, the next greater element is 10. For the fourth element 10, there is no next greater element, so return -1. For the fifth element 8, there is no next greater element, so return -1.

Example 2
Input
[3, 2, 1]
Output
[-1, -1, -1]

Explanation: There are no greater elements to the right of any element, so return -1 for all elements.

Example 3
Input
[1, 2, 3, 4, 5]
Output
[2, 3, 4, 5, -1]

Explanation: Each element has a next greater element to its right, except for the last element.

Constraints

  • 1 <= array length <= 10^4
  • -10^4 <= array elements <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free