Implement Stack

1. Implement the stack
2. Get Min value in stack with o(1)
3. Improve space complexity as well 

Code
import java.util.ArrayDeque;
import java.util.Deque;

interface IntStack {
    void push(int i);

    int pop();

    int peek();

    boolean empty();
}

class IntStackImpl implements IntStack {
    private Deque<Integer> dq;
    protected Deque<Integer> minStack;

    public IntStackImpl() {
        dq = new ArrayDeque<Integer>();
        minStack = new ArrayDeque<Integer>();
    }

    public boolean empty() {
        return dq.isEmpty();
    }

    public void push(int i) {
        dq.push(i);
        if (minStack.isEmpty()) {
            minStack.push(i);
        } else {
            int topValue = minStack.peek();
            if (i <= topValue) {
                minStack.push(i);
            }
        }
    }

    public int pop() {
        int value = dq.pop();
        if (minStack.peek() == value) {
            minStack.pop();
        }
        return value;
    }

    public int peek() {
        return dq.peek();
    }
}

interface MinStack extends IntStack {
    int min(); // gives minimum value without changing stack
}

class MinStackImpl extends IntStackImpl implements MinStack {

    // implement this
    public int min() {
        return minStack.peek();
    }
}

class Solution {
    public static void main(String[] args) {
        MinStack ms = new MinStackImpl();
        ms.push(5);
        System.out.println(ms.min()); //should print: 5
        ms.push(1);
        ms.push(3);
        System.out.println(ms.min()); //should print: 1
        System.out.println(ms.pop()); //should print: 3
        System.out.println(ms.min()); //should print: 1
        System.out.println(ms.pop()); //should print: 1
        System.out.println(ms.min()); //should print: 5
    }
}
Scroll to Top