← Stack Discipline

Micro-Drill #39 — Next greater element

Stack Discipline Target: 15s

Next-greater-element uses a decreasing stack. Shows up in stock span and temperature problems.

result = [-1] * len(a)
stack = []
for i in range(len(a) - 1, -1, -1):
    while stack and stack[-1] <= a[i]:
        stack.pop()
    if stack:
        result[i] = stack[-1]
    stack.append(a[i])

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #38 Micro #40 →