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.
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 indexjhasa[j] < a[i], we found the next greater element forj, so set answer forjtoa[i]and pop. - Push
ionto the stack.
Indices left in the stack have no greater element to the right, so their answer stays -1.
Time complexity is .
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