DevPath

← All problems

Next Greater Element

Easy stack · arrays

Description

For each element, return the first value to its right that is strictly greater, or -1 if there is none.

Constraints

1 <= n <= 100000

Examples

Input: nums = [2,1,2,4,3]

Output: [4,2,4,-1,-1]

Hints (1)
  • Scan right to left with a decreasing stack.

Solutions

Decreasing stack, resolve on a greater value. · Time O(n) · Space O(n)

func nextGreater(nums []int) []int {
    out := make([]int, len(nums))
    for i := range out {
        out[i] = -1
    }
    stack := []int{}
    for i, n := range nums {
        for len(stack) > 0 && nums[stack[len(stack)-1]] < n {
            out[stack[len(stack)-1]] = n
            stack = stack[:len(stack)-1]
        }
        stack = append(stack, i)
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account