Program to find circular greater element to the right in Python

The circular next greater element problem requires finding the next greater element to the right of each element in an array, with the array treated as circular. If no greater element exists, we assign -1.

For example, given [4, 5, 1, 3], the result is [5, -1, 3, 4] because:

  • 4's next greater element is 5

  • 5 has no greater element, so -1

  • 1's next greater element is 3

  • 3's next greater element is 4 (wrapping around)

Algorithm Steps

We use a stack-based approach with double iteration to handle the circular nature:

  • Initialize a stack with index 0 and result array filled with -1

  • Iterate through the array twice to simulate circular behavior

  • For each element, pop from stack while current element is greater than stack top element

  • Push current index to stack

Example

class Solution:
    def solve(self, nums):
        n = len(nums)
        stack, result = [0], [-1] * n
        
        # Double iteration for circular behavior
        for _ in range(2):
            for i in range(n):
                # While stack not empty and current element is greater
                while stack and nums[stack[-1]] < nums[i]:
                    result[stack[-1]] = nums[i]
                    stack.pop()
                stack.append(i)
        
        return result

# Test the solution
ob = Solution()
nums = [4, 5, 1, 3]
print("Input:", nums)
print("Output:", ob.solve(nums))
Input: [4, 5, 1, 3]
Output: [5, -1, 3, 4]

How It Works

The algorithm uses a monotonic decreasing stack to efficiently find next greater elements:

  1. First iteration: Processes elements normally, finding next greater elements within the array

  2. Second iteration: Handles circular cases where elements at the end find their next greater element at the beginning

Circular Next Greater Element 4 idx 0 5 idx 1 1 idx 2 3 idx 3 5 3 Circular: 4 ? (-1) Result: 5 -1 3 4 Legend: Found greater No greater (-1) Circular case

Time and Space Complexity

  • Time Complexity: O(n) - Each element is pushed and popped from stack at most once

  • Space Complexity: O(n) - For the stack and result array

Alternative Input Example

# Test with different array
nums2 = [2, 1, 2, 4, 3, 1]
ob = Solution()
result = ob.solve(nums2)
print("Input:", nums2)
print("Output:", result)
Input: [2, 1, 2, 4, 3, 1]
Output: [4, 2, 4, -1, 4, 2]

Conclusion

The circular next greater element problem is efficiently solved using a monotonic stack with double iteration. This approach handles both regular and circular cases in O(n) time complexity.

Updated on: 2026-03-25T10:45:13+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements