




Sponsored
Sponsored
This approach utilizes a stack to keep track of the indices of the elements for which we are finding the next greater element. We traverse the array twice (length times two) to account for the circular nature of the array. For each element, we repeatedly pop elements from the stack while the current element is greater than the element represented by the index at the top of the stack. As we pop elements, we update their next greater element in the resulting array. The stack helps ensure that each element is processed efficiently, leading to an O(n) complexity.
Time Complexity: O(n)
Space Complexity: O(n) (due to the stack and result array)
1public class Solution {
2    public int[] NextGreaterElements(int[] nums) {
3        int n = nums.Length;
4        int[] res = new int[n];
5        Array.Fill(res, -1);
6        Stack<int> stack = new Stack<int>();
7        for (int i = 0; i < 2 * n; i++) {
8            while (stack.Count > 0 && nums[stack.Peek()] < nums[i % n]) {
9                res[stack.Pop()] = nums[i % n];
10            }
11            if (i < n) stack.Push(i);
12        }
13        return res;
14    }
15}This C# implementation uses a stack-based solution. Iterating twice mimics the effect of a circular array, applying a modulo operation to map back to the actual indices of the array.
This approach uses two separate traversals to find the next greater element by checking for each element's greater counterpart. We double-iterate through the array copying elements to support cyclic checking. Though simpler conceptually, its efficiency isn't as optimal due to direct comparisons, and it could degrade to an O(n^2) complexity in worst cases. It's educational for understanding direct exhaustive search in circular constructs.
Time Complexity: O(n^2) in the worst case
This JavaScript approach checks each element's subsequent ones to find the next greater element. The use of nested loops highlights a brute-force method to illustrate the array's circular nature handling.