Algorithmsnext greater logic
Next Greater Element — Core Logic
TT
Testlaa Team
May 14, 2026•1 min read
Scanning left to right, the stack remembers candidates that still need a next greater value to their right.
Try this in Python
def next_greater(nums: list[int]) -> list[int | None]:
n = len(nums)
ans: list[int | None] = [None] * n
st: list[int] = []
for i in range(n - 1, -1, -1):
while st and st[-1] <= nums[i]:
st.pop()
ans[i] = st[-1] if st else None
st.append(nums[i])
return ans
print(next_greater([2, 4, 0, 9, 6]))
Key takeaways
- Reverse scan is one clean way to think “next on the right.”
- Forward-with-indices is equally common in interviews.
- Tie-breaking (
<=vs<) changes behavior—state it explicitly.
Tags:
Stacks & queuesPythonStudents
