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 changes as the input size grows.
How does the algorithm handle larger arrays efficiently?
Analyze the time complexity of the following code snippet.
void nextGreaterElement(int arr[], int n, int result[]) {
int stack[n];
int top = -1;
for (int i = n - 1; i >= 0; i--) {
while (top != -1 && stack[top] <= arr[i]) {
top--;
}
result[i] = (top == -1) ? -1 : stack[top];
stack[++top] = arr[i];
}
}
This code finds the next greater element for each item in the array using a stack.
- Primary operation: A single loop running from the end to the start of the array.
- How many times: The loop runs once for each element, so n times.
- Inside the loop: The while loop pops elements from the stack, but each element is pushed and popped at most once.
As the input size grows, each element is processed once, and stack operations happen at most once per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations (push/pop combined) |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: The total operations grow roughly in a straight line with input size.
Time Complexity: O(n)
This means the time to find the next greater element grows linearly with the number of elements.
[X] Wrong: "The nested while loop makes this algorithm O(n²)."
[OK] Correct: Each element is pushed and popped only once, so the total work inside the while loops across all iterations is still proportional to n.
Understanding this linear time stack approach shows you can solve problems efficiently by avoiding repeated work, a key skill in coding interviews.
What if we changed the input to a linked list instead of an array? How would the time complexity change?
Practice
Solution
Step 1: Understand the problem definition
The Next Greater Element problem asks for the first element to the right of each element that is greater than it.Step 2: Identify the role of the stack
The stack helps efficiently find this next greater element by storing candidates and popping smaller elements.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
- Looking to the left instead of right
- Thinking it sums elements instead of finding one
Solution
Step 1: Check valid C array and top initialization
int stack[100]; int top = -1; declares a fixed size array and sets top to -1 indicating empty stack.Step 2: Identify invalid syntax or semantics in other options
int stack[] = {0}; int top = 0; initializes top to 0 which means stack is not empty; int *stack; int top = NULL; uses NULL for int top which is invalid; stack = new int[100]; top = -1; uses 'new' which is C++ syntax, not C.Final Answer:
int stack[100]; int top = -1; -> Option AQuick Check:
Stack array + top = -1 means empty [OK]
- Using C++ 'new' keyword in C code
- Initializing top to 0 instead of -1
- Using pointer without allocation
[4, 5, 2, 25] using the stack method?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: Confirm output array
The output array is [5, 25, 25, -1].Final Answer:
[5, 25, 25, -1] -> Option CQuick Check:
Next greater elements match output [OK]
- Assigning smaller or wrong next greater values
- Using -1 for elements that do have greater elements
- Confusing order of output
for (int i = 0; i < n; i++) {
while (top != -1 && arr[stack[top]] < arr[i]) {
result[stack[top]] = arr[i];
top--;
}
stack[++top] = i;
}
while (top != -1) {
result[stack[top]] = 0;
top--;
}Solution
Step 1: Check final assignment for elements with no next greater
The code assigns 0 instead of -1, which is incorrect as per problem definition.Step 2: Verify other parts of code
Stack index increment and loop conditions are correct; top is assumed initialized before.Final Answer:
Assigning 0 instead of -1 for elements with no greater element -> Option BQuick Check:
No greater element should be -1, not 0 [OK]
- Using 0 instead of -1 for no next greater
- Forgetting to initialize top
- Wrong increment operator on stack
[13, 7, 6, 12], what is the Next Greater Element array using the stack approach? Also, explain why the last element's next greater is -1.Solution
Step 1: Find next greater for each element
For 13, no greater element to right, so -1; for 7, next greater is 12; for 6, next greater is 12; for 12, no greater element, so -1.Step 2: Explain last element's next greater
The last element 12 has no elements to its right, so no next greater element exists, hence -1.Final Answer:
[ -1, 12, 12, -1 ] -> Option DQuick Check:
Last element no right neighbor = -1 [OK]
- Assigning next greater to last element
- Mixing up next greater for middle elements
- Confusing output order
Ready to prove it?
Pass the test and this pattern moves unknown
