How to Find the Next Greater Element for Each List Item in Python

Use a monotonic stack to find the next greater element to the right for every item in a list, in O(n) time.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

16 lines
Python 3.9+
def next_greater_element(nums):
    result = [-1] * len(nums)
    stack = []
    
    for i in range(len(nums) - 1, -1, -1):
        while stack and stack[-1] <= nums[i]:
            stack.pop()
        result[i] = stack[-1] if stack else -1
        stack.append(nums[i])
    
    return result


if __name__ == "__main__":
    sample = [4, 5, 2, 25, 10]
    print(next_greater_element(sample))

Output

stdout
[5, 25, 25, -1, -1]

How it works

The function iterates from right to left, maintaining a stack that holds potential next greater elements for the current index. While the top of the stack is less than or equal to the current value, it's popped because it can't be the answer for any earlier element. The top after popping is the next greater element (or -1 if the stack is empty). The current value is then pushed to act as a candidate for earlier indices. This ensures each element is pushed and popped once, yielding O(n) time.

Common mistakes

  • Forgetting that equal elements don't count as greater, so you need `<=` in the while condition.
  • Returning the element itself when no greater element exists instead of -1.
  • Mixing up the direction — scanning left to right requires a different approach with an output array.

Variations

  1. Find the next greater element to the left by scanning left to right with the same stack logic.
  2. Use a dictionary to map each element to its next greater element for more complex lookups.

Real-world use cases

  • Computing spans in stock prices: for each day, how far back the price stayed lower — a standard financial indicator.
  • Solving the 'daily temperatures' problem in LeetCode by finding the number of days until a warmer temperature.
  • Parsing nested structures like parentheses matching where you need the next matching delimiter position.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.