Get minimum from an stack in O(1) time.
Using two stacks it can be done, first stack will store normal values and second stack (minStack) will store only min values so when we will pop min value from stack we will also check in minStack either its having the same value if yes then will pop() value from both stack, and in minStack will get another min value on top.
public class MinFromStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
int min = Integer.MAX_VALUE;
public static void main(String[] args) {
int[] n = { -7,2, 3, 1, 2, -1, -4, 8, 9,-10 };
MinFromStack s = new MinFromStack();
for (int i : n) {
s.pushTostack(i);
}
s.printMinstack();
s.printStack();
s.popStack();
s.popStack();
s.popStack();
s.popStack();
s.printMinstack();
}
void pushTostack(int n) {
if (n < min) {
min = n;
minStack.push(n);
}
stack.push(n);
}
int popStack() {
if (stack.peek() == minStack.peek()) {
minStack.pop();
}
return stack.pop();
}
int getMin() {
return minStack.peek();
}
void printStack() {
System.out.println(stack);
}
void printMinstack() {
System.out.println(minStack);
}
}
Using two stacks it can be done, first stack will store normal values and second stack (minStack) will store only min values so when we will pop min value from stack we will also check in minStack either its having the same value if yes then will pop() value from both stack, and in minStack will get another min value on top.
public class MinFromStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
int min = Integer.MAX_VALUE;
public static void main(String[] args) {
int[] n = { -7,2, 3, 1, 2, -1, -4, 8, 9,-10 };
MinFromStack s = new MinFromStack();
for (int i : n) {
s.pushTostack(i);
}
s.printMinstack();
s.printStack();
s.popStack();
s.popStack();
s.popStack();
s.popStack();
s.printMinstack();
}
void pushTostack(int n) {
if (n < min) {
min = n;
minStack.push(n);
}
stack.push(n);
}
int popStack() {
if (stack.peek() == minStack.peek()) {
minStack.pop();
}
return stack.pop();
}
int getMin() {
return minStack.peek();
}
void printStack() {
System.out.println(stack);
}
void printMinstack() {
System.out.println(minStack);
}
}