Interesting Python Implementation for Next Greater Elements

In this article, we will learn how to find the Next Greater Element for each element in an array. The Next Greater Element is the first larger element that appears to the right of the current element in the array.

Problem Statement

Given an array of integers, we need to find the Next Greater Element for every element. For elements that don't have a greater element on their right side, we return -1.

Example Input and Output

For the array [12, 1, 2, 3] ?

12 ? -1  (no element greater than 12 on the right)
1 ? 2    (first greater element is 2)
2 ? 3    (first greater element is 3)
3 ? -1   (no element greater than 3 on the right)

Implementation Using Linear Search

Here's a simple approach that checks each element against all elements to its right ?

def find_next_greater_element(arr):
    """Find next greater element for each element in array"""
    
    for i in range(len(arr)):
        next_greater = -1
        
        # Search for next greater element on the right
        for j in range(i + 1, len(arr)):
            if arr[j] > arr[i]:
                next_greater = arr[j]
                break
        
        print(f"{arr[i]} ? {next_greater}")

# Test with sample arrays
arr1 = [12, 1, 2, 3]
print("Array 1:", arr1)
find_next_greater_element(arr1)

print("\nArray 2:", [1, 34, 2, 1])
arr2 = [1, 34, 2, 1]
find_next_greater_element(arr2)
Array 1: [12, 1, 2, 3]
12 ? -1
1 ? 2
2 ? 3
3 ? -1

Array 2: [1, 34, 2, 1]
1 ? 34
34 ? -1
2 ? -1
1 ? -1

Optimized Stack-Based Solution

For better performance, we can use a stack to solve this problem in O(n) time complexity ?

def next_greater_element_optimized(arr):
    """Find next greater elements using stack (O(n) solution)"""
    
    result = [-1] * len(arr)  # Initialize result array
    stack = []  # Stack to store indices
    
    for i in range(len(arr)):
        # While stack is not empty and current element is greater
        # than element at index stored at top of stack
        while stack and arr[i] > arr[stack[-1]]:
            index = stack.pop()
            result[index] = arr[i]
        
        stack.append(i)
    
    # Print results
    for i in range(len(arr)):
        print(f"{arr[i]} ? {result[i]}")

# Test the optimized solution
arr = [4, 5, 2, 25, 7, 8]
print("Array:", arr)
next_greater_element_optimized(arr)
Array: [4, 5, 2, 25, 7, 8]
4 ? 5
5 ? 25
2 ? 25
25 ? -1
7 ? 8
8 ? -1

Comparison

Approach Time Complexity Space Complexity Best For
Linear Search O(n²) O(1) Small arrays, simple implementation
Stack-based O(n) O(n) Large arrays, optimal performance

Conclusion

The Next Greater Element problem can be solved using linear search for simplicity or a stack-based approach for optimal performance. The stack solution is preferred for large datasets as it reduces time complexity from O(n²) to O(n).

Updated on: 2026-03-25T06:19:01+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements