880822. Get min at pop
Easy
Here is a detailed Markdown blog post for the problem "Get min at pop":
Get Min at Pop
Summary
The "Get min at pop" problem involves designing an algorithm to find and maintain the minimum value in a stack. This problem requires understanding of basic data structures, specifically stacks, and how to efficiently manage them.
Detailed Explanation
When we say "get min at pop", it means that whenever we pop an element from the stack, we need to get the minimum element among all the elements popped so far. We can achieve this by using a secondary stack to keep track of the minimum elements.
Here's a step-by-step breakdown of the solution:
- Initialize two stacks:
mainStackandminStack.mainStackwill store the actual elements, whileminStackwill store the minimum elements. - Push the first element from
mainStackontominStackas well, since it's the only element so far. - For each subsequent push operation:
- If the pushed element is less than or equal to the top of
minStack, push it onto both stacks. - Otherwise, pop all elements from
minStackuntil the top element is smaller than or equal to the pushed element. Then, push this new minimum element and the pushed element onto both stacks.
- If the pushed element is less than or equal to the top of
- For each pop operation:
- Pop the top element from
mainStack. This will be the element we're interested in. - Find the minimum of all elements popped so far by popping and comparing the top elements from
minStackuntil we find the minimum. This is our answer.
- Pop the top element from
Time Complexity: O(n), where n is the number of push/pop operations. Space Complexity: O(n), since we need to store at most n-1 elements in both stacks.
Optimized Solutions
Java
class GetMinAtPop {
public static int getMin(Stack<Integer> mainStack) {
Stack<Integer> minStack = new Stack<>();
int min = mainStack.pop();
minStack.push(min);
for (int x : mainStack) {
if (x <= min) {
min = x;
minStack.push(x);
mainStack.push(x);
} else {
while (!minStack.isEmpty() && minStack.peek() > x) {
minStack.pop();
}
minStack.push(min);
mainStack.push(x);
}
}
return min;
}
}