Editorial for Next Greater Element


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Approach

Use a monotonic decreasing stack of indices.

While scanning the array from left to right:

  • Keep indices in the stack such that their values are in non-increasing order.
  • For current index i, while the top index j has a[j] < a[i], we found the next greater element for j, so set answer for j to a[i] and pop.
  • Push i onto the stack.

Indices left in the stack have no greater element to the right, so their answer stays -1.

Time complexity is O(n).

Solution (Python)

n = int(input())
a = [int(x) for x in input().split()]

ans = [-1] * n
stack: list[int] = []

for i in range(n):
    while stack and a[stack[-1]] < a[i]:
        ans[stack.pop()] = a[i]
    stack.append(i)

print(" ".join(str(x) for x in ans))

Comments

There are no comments at the moment.