What if you could always know the smallest item in your stack instantly, no matter how big it is?
0
0
Why Min Stack Design in DSA C?
The Big Idea
The Scenario
Imagine you have a stack of books and you want to quickly find the smallest book without taking all books out.
The Problem
Checking each book one by one every time to find the smallest is slow and tiring, especially if the stack is tall.
The Solution
A Min Stack keeps track of the smallest book at every step, so you can know the smallest instantly without searching.
Before vs After
✗ Before
int findMin(int stack[], int size) {
int min = stack[0];
for (int i = 1; i < size; i++) {
if (stack[i] < min) min = stack[i];
}
return min;
}✓ After
typedef struct {
int value;
int currentMin;
} StackNode;
void push(StackNode stack[], int *top, int val) {
int min = (*top == -1) ? val : (val < stack[*top].currentMin ? val : stack[*top].currentMin);
stack[++(*top)] = (StackNode){val, min};
}
What It Enables
You can get the smallest value in the stack instantly, making your program faster and smarter.
Real Life Example
In a game, quickly knowing the lowest score so far helps decide the next move without checking all scores again.
Key Takeaways
Manual search for minimum is slow and repetitive.
Min Stack stores minimum at each step for quick access.
Improves speed and efficiency in stack operations.
