155. Min Stack#

Courtesy: fishercoder1534

Approach 1#

Using a min variable to store the current minimum value. While pushing

Code#

 1class MinStack {
 2
 3  Stack<Integer> stk;
 4  int min;
 5
 6  public MinStack() {
 7    stk = new Stack<>();
 8    min = Integer.MAX_VALUE;
 9  }
10
11  public void push(int val) {
12    if (val <= min) {
13      stk.push(min);
14      min = val;
15    }
16    stk.push(val);
17  }
18
19  public void pop() {
20    if (min == stk.pop()) {
21      min = stk.pop();
22    }
23  }
24
25  public int top() {
26    return stk.peek();
27  }
28
29  public int getMin() {
30    return min;
31  }
32}
33/**
34 * Your MinStack object will be instantiated and called as such:
35 * MinStack obj = new MinStack();
36 * obj.push(val);
37 * obj.pop();
38 * int param_3 = obj.top();
39 * int param_4 = obj.getMin();
40 */