# Simple Java solution 12 line

• class MinStack {

``````Stack<Integer> stack=new Stack<>();
int min=Integer.MAX_VALUE;
public void push(int x) {
if(x<=min) {stack.push(min); min=x;}
stack.push(x);
}
public void pop() {
if(stack.peek()==min){ stack.pop(); min=stack.pop(); }
else stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
``````

}

• class MinStack {

``````List<Integer> s = new LinkedList();
List<Integer> q = new LinkedList();

public void push(int x) {
else if(x <= q.get(q.size()-1)) q.add(x);
}

public void pop() {
if(s.size()<1) return;
if(top() == q.get(q.size()-1)) q.remove(q.size()-1);
s.remove(s.size()-1);
}

public int top() {
if(s.size()<1) return 0;
return s.get(s.size()-1);
}

public int getMin() {
return q.get(q.size()-1);
}
``````

}

• good idea . push twice if min

• good idea . push twice if min

• Thanks for sharing such brilliant solution!

• Note: This would result in roughly the same memory allocation as two stacks in the worst case (continuously pushing smaller numbers).

• very nice sol. Appreciate for sharing!

• what a good idea

• What a good Idea!
push min and x, if x is min.

• Clean solution, thank you!

• This is intelligent idea. Idea is to track the minimum value at every element.The same solution in CTCI asks you to maintain an linear memory to track min for each push. Here you are saving space this way.

• You can write pop like this to make it shorter.

``````public void pop() {
if (minStack.pop() == min) min = minStack.pop();
}
``````

• I think there is a problem.
Example:
push(2);
push(0);
pop();
pop();
getMin();

Last line will return Integer.MAX_VALUE; And in fact it is supposed to be null since the stack is empty now.

• @shaoqing The last line won't return Integer MAX_VALUE, because this value is denoted to min in “min=stack.pop();” and correspondingly, the value in stack is deleted by pop()

• @SeaLanding yes, it is deleted, but this.min has been set to Integer.MAX_VALUE, and what @shaoqing was saying was that, the getMin() will return Integer.MAX_VALUE, even when stack is empty, and therefore saying the original post is lack of code handling this case!

• @SeaLanding Integer.MAX_VALUE is pushed into the stack at the first time push any number in. So even we pop the same amount of time as push, there is extra number in the stack, which is MAX_VALUE. Run the code and you will see.

• @xuehaohu You got it.

• @shaoqing Guess original code serves a great example to demonstrate the logic to solve the problem, individual submission need more work on handling possible any edge/corner case.

• why it won't ac if i change "x<=min" to "x<min" in push function?

• @slowdownzhu Oh, i see! Because it will pop() twice when x==min!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.