DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS
Find Next Greater Elements with a Monotonic Stack
Learn how to find next greater elements with a monotonic stack using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
5 10 10 -1 -1
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[] = {4, 5, 2, 10, 8};
int result[5], stack[5], top = -1;
for (int index = 4; index >= 0; index--) {
while (top >= 0 && stack[top] <= values[index]) top--;
result[index] = top < 0 ? -1 : stack[top];
stack[++top] = values[index];
}
for (int index = 0; index < 5; index++) printf("%d ", result[index]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
5 10 10 -1 -1
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Keep only useful larger values to the right in a decreasing stack.
- Display the computed result.
Keep only useful larger values to the right in a decreasing stack.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
