Mid From PDF Coding C# Coding Interview

Find the next greater element for every element in an array?

int[] NextGreaterElements(int[] nums) {
int n = nums.Length;
int[] result = 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();

}
result[i] = stack.Count == 0 ? -1 : stack.Peek();

stack.Push(nums[i]);

}
return result;
}

Explanation:

Traverse from right to left, use stack to keep track of next greater elements in O(n).

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details