Back to exercises

Next Greater Element

Walk the array from right to left and maintain a stack of candidates greater than the current value. Pop smaller values because they can never be the next greater element for earlier entries.

Coding Exercises Medium O(n)

Next Greater Element

Walk the array from right to left and maintain a stack of candidates greater than the current value. Pop smaller values because they can never be the next greater element for earlier entries.

For each element in an array, return the next greater element to its right, or -1 if none exists.