• Time:O(n)
• Space:O(n)

## C++

``````class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
const int n = nums.size();
vector<int> ans(n, -1);
stack<int> stack;  // decreasing stack storing indices

for (int i = 0; i < n * 2; ++i) {
const int num = nums[i % n];
while (!stack.empty() && nums[stack.top()] < num)
ans[stack.top()] = num, stack.pop();
if (i < n)
stack.push(i);
}

return ans;
}
};
``````

## JAVA

``````class Solution {
public int[] nextGreaterElements(int[] nums) {
final int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, -1);
Deque<Integer> stack = new ArrayDeque<>(); // decreasing stack storing indices

for (int i = 0; i < n * 2; ++i) {
final int num = nums[i % n];
while (!stack.isEmpty() && nums[stack.peek()] < num)
ans[stack.pop()] = num;
if (i < n)
stack.push(i);
}

return ans;
}
}
``````

## Python

``````class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [-1] * n
stack = []

for i in range(n * 2):
num = nums[i % n]
while stack and nums[stack[-1]] < num:
ans[stack.pop()] = num
if i < n:
stack.append(i)

return ans
``````