Next Greater Element

Stack Data Structures Easy Medium

Next Greater Element

Given an array of integers, your task is to find the next greater element for each element in the array. For each element in the array, the next greater element is the first element to its right that is greater than it. If no such element exists, use -1 for that position.

Example

For the input:

[2, 7, 3, 5, 4, 6, 8]

The output should be:

[7, 8, 5, 6, 6, 8, -1]

Guidelines

  • Use a stack to efficiently solve this problem. The stack should help you keep track of candidates for the next greater element as you iterate through the array.
  • Aim for a solution with a time complexity of O(n).
  • This problem is a great exercise in stack usage and array manipulation.

Note: Today (March 13, 2025) reminds us of the thoughtful integration of historical algorithms with modern coding practices. Enjoy the challenge and happy coding!

Starter Code

Below is some starter code for various programming languages to help you begin your solution. Fill in the logic where indicated.