Skip to content

Instantly share code, notes, and snippets.

@omargfh
Created November 29, 2022 21:47
Show Gist options
  • Save omargfh/ad4512c980332053aa89ddddd84489a2 to your computer and use it in GitHub Desktop.
Save omargfh/ad4512c980332053aa89ddddd84489a2 to your computer and use it in GitHub Desktop.
class MinStack {
#stack = [];
#history = [Number.POSITIVE_INFINITY];
constructor() {}
push(val: number): void {
this.#stack.push(val);
if (val <= this.#history[this.#history.length - 1]) {
this.#history.push(val);
}
}
pop(): void {
const popped = this.#stack.pop();
if (popped === this.#history[this.#history.length - 1]) {
this.#history.pop();
}
}
top(): number {
return this.#stack[this.#stack.length - 1];
}
getMin(): number {
return this.#history[this.#history.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()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment