BackeasyStack Amazon

Next Greater Element Solution

Problem Statement

Given an array of integers, find the next greater element for each element in the array.

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

Explanation: Step-by-step: For input [4, 5, 2, 25], we iterate through the array from left to right. When we encounter 2, we find the next greater element 5. For the rest of the elements, we find the next greater element as -1.

Example 2
Input
[13, 7, 6, 12]
Output
[13, 12, -1, -1]

Explanation: Step-by-step: For input [13, 7, 6, 12], we iterate through the array from left to right. When we encounter 7, we find the next greater element 12. For the rest of the elements, we find the next greater element as -1.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= 10^9
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