## Similar Problems

Similar Problems not available

# Next Greater Element Iii - Leetcode Solution

LeetCode: Next Greater Element Iii Leetcode Solution

Difficulty: Medium

Topics: math string two-pointers

Problem statement:

Given a circular array containing n elements, find the next greater element for every element in the array in a circular fashion. The next greater element of an element x is the first greater element to its right in the circular array. If it does not exist, output -1 for this element.

Example:

Input: [1,2,1]

Output: [2,-1,2]

Explanation:

The first 1's next greater element is 2;

The second 2 cannot be greater than itself (element on the right is the same), so output -1;

The last 1 has next greater element as 2 (the first occurrence of number 2 is at a circular index of 1, which is greater than the index of the current element).

Solution:

As the array is circular, we need to traverse it twice to find the next greater element for every element in the array.

We can achieve this by using a stack and iterating the array twice. In the first iteration, we will find the next greater element for every element to its right. In the second iteration, we will find the next greater element for every element left to that element.

To find the next greater element to the right, we push the elements onto the stack until we find a larger element. The larger element will be the next greater element for all the previous elements in the stack - we pop those elements from the stack and update their next greater element to be the current element.

To find the next greater element to the left, we follow the same approach but in reverse direction. We push the elements onto the stack until we find a larger element. The larger element will be the next greater element for all the previous elements in the stack - we pop those elements from the stack and update their next greater element to be the current element.

At the end of both iterations, the array will contain the next greater element for every element in the circular array.

Here's the Python code to implement this approach:

def nextGreaterElements(nums: List[int]) -> List[int]:

```
n = len(nums)
result = [-1] * n
stack = []
# Iteration 1: Find next greater element to the right
for i in range(n * 2):
while stack and nums[stack[-1]] < nums[i % n]:
result[stack.pop()] = nums[i % n]
stack.append(i % n)
# Iteration 2: Find next greater element to the left
for i in range(n * 2):
while stack and nums[stack[-1]] < nums[i % n]:
result[stack.pop()] = nums[i % n]
if i < n:
stack.append(i)
return result
```

Time complexity: O(n)

Space complexity: O(n) (stack size)

## Next Greater Element Iii Solution Code

`1`