Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Last active January 26, 2026 01:06
Show Gist options
  • Select an option

  • Save Ephraimiyanda/2e2d6d9a970ecd9e1ff546ce169dda11 to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/2e2d6d9a970ecd9e1ff546ce169dda11 to your computer and use it in GitHub Desktop.
Mun Stack

Approach

  1. minStack always stores the current minimum.
  2. push to minStack only if it’s a new minimum.
  3. pop from minStack only if ive removed the minimum.

Complexity

  • Time complexity:O(1)

  • Space complexity:O(N)

Code

class MinStack {
    private stack: number[];
    private minStack: number[];

    constructor() {
        this.stack = [];
        this.minStack = [];
    }

    push(val: number): void {

        this.stack.push(val)
        if (
            this.minStack.length === 0 ||
            val <= this.minStack[this.minStack.length - 1]
        ) {
            this.minStack.push(val);
        }
    }

    pop(): void {
      
        if ( this.stack.pop()=== this.minStack[this.minStack.length - 1]) {
            this.minStack.pop();
        }
    }

    top(): number {
        return this.stack[this.stack.length - 1]
    }

    getMin(): number {
        return this.minStack[this.minStack.length - 1]
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */
scrnli_zqrAQ5Uq2goegl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment