JSFiddle - React, Tailwind, and code Playground

by Krishna Ananthi

JavaScript

class MinStack {
    constructor() {
        this.min = Infinity;
        this.stack = [];
    }

    /**
     * @param {number} val
     * @return {void}
     */
    push(val) {
        if (this.stack.length === 0) {
            this.stack.push(0);
            this.min = val;
        } else {
            this.stack.push(val - this.min);
            if (val < this.min) this.min = val;
        }
        console.log(this.stack, this.min)
    }

    /**
     * @return {void}
     */
    pop() {
        if (this.stack.length === 0) return;

        const pop = this.stack.pop();

        if (pop < 0) this.min -= pop;
        console.log(this.stack, this.min)
    }

    /**
     * @return {number}
     */
    top() {
        const top = this.stack[this.stack.length - 1];
        return top > 0 ? top + this.min : this.min;
        console.log(this.stack, this.min)
    }

    /**
     * @return {number}
     */
    getMin() {
        return this.min;
    }
}

let s = new MinStack();
s.push(10);
s.push(3)
s.push(2)
s.push(4)
s.push(1)
s.pop()
s.pop()
s.top()