Javascript solution O(1) with intuitive stack that inherits array.


  • 0

    Javascript solution O(1) with intuitive stack that inherits array.

    /**
     * initialize your data structure here.
     */
    var MinStack = function() {
        this.super = (method, arg) => Array.prototype[method].call(this,arg);
        this.min = [];
        this.getMin = ()=>this.min.length?this.min[this.min.length-1]:Infinity;
    };
    
    MinStack.prototype = Object.create(Array.prototype);
    
    MinStack.prototype.pop = function() {
        if( this.min.length && this.top() === this.getMin() ) this.min.pop();
        return this.super('pop');
    }
    
    MinStack.prototype.push = function(x) {
        if(this.min.length === 0 ||  this.getMin() >= x) this.min.push(x);
        return this.super('push',x);
    };
    
    MinStack.prototype.top = function() {
        if( this.length === 0 ) return undefined;
        console.log(this);
        return this[this.length-1];
    };
    
    

Log in to reply
 

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