Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
First iteration: Processes elements normally, finding next greater elements within the array
Second iteration: Handles circular cases where elements at the end find their next greater element at the beginning
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.
