using System; using System.Collections.Generic; class Program { static void Main() { int[] arr = {4, 5, 2, 25}; int[] result = NextGreaterElement(arr); foreach (int val in result) { Console.Write(val + " "); } } static int[] NextGreaterElement(int[] nums) { int n = nums.Length; int[] res = new int[n]; Stack<int> stack = new Stack<int>(); for (int i = n - 1; i >= 0; i--) { while (stack.Count > 0 && stack.Peek() <= nums[i]) { stack.Pop(); } res[i] = stack.Count == 0 ? -1 : stack.Peek(); stack.Push(nums[i]); } return res; } }
The algorithm processes the array from right to left. For each element, it pops smaller or equal elements from the stack until it finds a greater element or the stack is empty. The next greater element is the top of the stack or -1 if none exists.
For the array [4, 5, 2, 25]:
- 25 has no greater element to the right → -1
- 2's next greater is 25
- 5's next greater is 25
- 4's next greater is 5
The stack stores elements in decreasing order from top to bottom. When processing from right to left, smaller elements are popped out, so the top always holds the next greater element candidate. This avoids scanning all elements repeatedly.
int[] NextGreaterElement(int[] nums) { int n = nums.Length; int[] res = new int[n]; Stack<int> stack = new Stack<int>(); for (int i = 0; i < n; i++) { while (stack.Count > 0 && stack.Peek() <= nums[i]) { stack.Pop(); } res[i] = stack.Count == 0 ? -1 : stack.Peek(); stack.Push(nums[i]); } return res; }
The standard Next Greater Element algorithm using a stack requires processing the array from right to left. Processing from left to right as in this code will not correctly find the next greater elements, leading to wrong results.
using System; using System.Collections.Generic; class Program { static void Main() { int[] arr = {1, 2, 1}; int[] result = NextGreaterElementCircular(arr); foreach (int val in result) { Console.Write(val + " "); } } static int[] NextGreaterElementCircular(int[] nums) { int n = nums.Length; int[] res = new int[n]; Stack<int> stack = new Stack<int>(); for (int i = 2 * n - 1; i >= 0; i--) { while (stack.Count > 0 && stack.Peek() <= nums[i % n]) { stack.Pop(); } res[i % n] = stack.Count == 0 ? -1 : stack.Peek(); stack.Push(nums[i % n]); } return res; } }
For the circular array [1, 2, 1]:
- Next greater for 1 (index 0) is 2
- Next greater for 2 (index 1) does not exist → -1
- Next greater for 1 (index 2) is 2 (from index 1)
Next greater elements:
- 13 → no greater element → -1
- 7 → next greater is 12
- 6 → next greater is 12
- 12 → no greater element → -1
Elements with no next greater element: 13 and 12 → 2 elements.
