---
# System prepended metadata

title: 155. Min Stack
tags: [Stack]

---

---
title: 155. Min Stack
tags: Stack
description: share source code.
---

# 155. Min Stack

```java

// used Pair always keep track of min value
class MinStack {

    static class Pair{
        int val;
        int min;
        public Pair(int val, int min){
            this.val = val;
            this.min = min;
        }
    }
    
    Stack<Pair> sk;
    
    public MinStack() {
        sk = new Stack<>();
    }
    
    public void push(int val) {
        if(sk.isEmpty()){
            sk.push(new Pair(val, val));
        }else{
           sk.push(new Pair(val, Math.min(val, sk.peek().min))); 
        }
        
    }
    
    public void pop() {
        sk.pop();
    }
    
    public int top() {
        return sk.peek().val;
    }
    
    public int getMin() {
        return sk.peek().min;
    }
}
```