Next Greater Element Using Stack in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the next greater element grows as the input list gets bigger.
How does the number of steps change when we use a stack to solve this problem?
Analyze the time complexity of the following code snippet.
public int[] NextGreaterElement(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;
}
This code finds the next greater element for each number in the array using a stack, scanning from right to left.
- Primary operation: The for-loop runs once for each element from right to left.
- Inside the loop: The while-loop pops smaller or equal elements from the stack.
- How many times: Each element is pushed once and popped at most once, so total stack operations are at most 2n.
As the input size grows, each element is processed a limited number of times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: The total operations grow roughly in a straight line with input size, not faster.
Time Complexity: O(n)
This means the time to find next greater elements grows directly in proportion to the number of elements.
[X] Wrong: "Because there is a nested while inside the for-loop, the time complexity must be O(n²)."
[OK] Correct: Each element is pushed and popped only once, so the total work inside the while-loop across all iterations is limited to O(n), not multiplied by n.
Understanding this pattern helps you solve many problems efficiently using stacks, a skill often valued in interviews.
"What if we changed the input to a circular array where the search wraps around? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The Next Greater Element problem asks to find, for each element, the first element to its right that is greater than it.Step 2: Identify the role of the stack
A stack helps track elements for which we haven't found a greater element yet, allowing efficient lookup of the next greater element.Final Answer:
The first greater element to the right of each element -> Option AQuick Check:
Next Greater Element = first greater right element [OK]
- Confusing next greater with next smaller element
- Thinking it finds the maximum element overall
- Assuming it finds elements to the left instead of right
Solution
Step 1: Identify correct stack initialization syntax in C#
Using generic Stack<int> with new Stack<int>() is the modern and type-safe way to create a stack of integers.Step 2: Compare other options
Stack stack = new Stack(); uses non-generic Stack (older style), C uses List which is not a stack, D uses array which is fixed size and not a stack.Final Answer:
Stack<int> stack = new Stack<int>(); -> Option DQuick Check:
Generic Stack<int> initialization is correct [OK]
- Using non-generic Stack without type safety
- Using List instead of Stack for LIFO behavior
- Using fixed-size arrays instead of dynamic stack
[4, 5, 2, 25]?Solution
Step 1: Process each element to find next greater
For 4, next greater is 5; for 5, next greater is 25; for 2, next greater is 25; for 25, no greater element, so -1.Step 2: Form the output array
Output array is [5, 25, 25, -1].Final Answer:
[5, 25, 25, -1] -> Option AQuick Check:
Next Greater Elements = [5, 25, 25, -1] [OK]
- Assigning -1 too early for elements with greater elements later
- Confusing next greater with next smaller
- Misreading the input array order
int[] arr = {2, 7, 3, 5, 4, 6, 8};
Stack<int> stack = new Stack<int>();
int[] result = new int[arr.Length];
for (int i = 0; i < arr.Length; i++) {
while (stack.Count > 0 && arr[stack.Peek()] < arr[i]) {
result[stack.Pop()] = arr[i];
}
stack.Push(i);
}
while (stack.Count > 0) {
result[stack.Pop()] = 0;
}Solution
Step 1: Check how no greater elements are marked
The code assigns 0 to elements with no next greater element, but conventionally -1 is used to indicate none.Step 2: Verify other parts of the code
Indices are pushed, arr[stack.Peek()] is correctly used, and result array is initialized, so no errors there.Final Answer:
Assigning 0 instead of -1 for elements with no greater element -> Option BQuick Check:
No greater element marked as -1, not 0 [OK]
- Using 0 instead of -1 for no greater element
- Pushing values instead of indices on stack
- Incorrect while loop condition
[13, 7, 6, 12], how would you modify the Next Greater Element algorithm to find the next greater element to the left instead of the right?Solution
Step 1: Understand direction change for next greater to left
To find next greater element on the left, we must scan from left to right, checking elements before current.Step 2: Use stack to track candidates and pop smaller elements
We push elements and pop smaller ones to find the nearest greater on the left efficiently.Final Answer:
Traverse the array from left to right and use a stack to track elements, popping smaller ones. -> Option CQuick Check:
Next greater left = left to right traversal with stack [OK]
- Scanning right to left for next greater left
- Using queue instead of stack
- Popping greater elements instead of smaller
Ready to prove it?
Pass the test and this pattern moves unknown
