Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Min Stack #57

Open
kokocan12 opened this issue Jul 4, 2022 · 0 comments
Open

Min Stack #57

kokocan12 opened this issue Jul 4, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

Problem

Implement Min Stack, min stack is same as normal stack but, it has function that return the min value of stack.
Min Stack has to have push, pop, getMin, top methods, each method has a time complexity of O(1).

Approach

Managing values in stack, and minStack.
minStack is used for saving values those are less than getMin() or same.

The code is below.

/**
 *   Stack = [-2]
 *   minStack = [-2]
 *
 *   Stack = [-2, 0]
 *   minStack = [-2] Zero is not pushed to minStack, because 0 is not less than getMin().
 *
 *   Stack = [-2, 0, -3]
 *   minStack = [-2, -3] minValues is managed by minStack.
 *
 *   Stack = [-2, 0]
 *   minStack = [-2]
 *   
 *   Stack = [-2, 0, -3]
 *   minStack = [-2, -3]
 *
 *   Stack = [-2, 0, -3, -3]
 *   minStack = [-2,-3,-3] Value is pushed to minStack when value is less than getMin() OR same as.
 *
 *   Stack = [-2, 0, -3]
 *   minStack = [-2,-3] minStack value is poped when stack is poped and the value is same as getMin().
 *   
 */


const MinStack = function() {
    this.stack = [];
    this.minStack = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {
    this.stack.push(val);
    
    const currentMin = this.getMin();
    if(currentMin === null || currentMin >= val) {
        this.minStack.push(val);
    }
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    const popedValue = this.stack.pop();
    
    if(popedValue === this.getMin()) {
        this.minStack.pop();
    }
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.stack[this.stack.length - 1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    if(this.minStack.length === 0) {
        return null;
    } 
    return this.minStack[this.minStack.length - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant