Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Shuumatsu/ae0b6bb1f968a1cd7a2b88c36ac9090e to your computer and use it in GitHub Desktop.
Save Shuumatsu/ae0b6bb1f968a1cd7a2b88c36ac9090e to your computer and use it in GitHub Desktop.
a stack that supports getMin() in O(1) time and O(1) extra space
export class MinStack {
stack: number[] = [];
num: number = 0;
private _min: number;
get min(): number {
if (this.num > 0) {
return this._min;
}
}
push(el: number) {
this.num++;
if (this.num === 1) {
this.stack.push(el);
this._min = el;
return;
}
if (el >= this.min) {
this.stack.push(el);
return;
}
this.stack.push(2 * el - this.min);
this._min = el;
}
pop(): number {
if (this.num === 0) {
return;
}
this.num--;
let el = this.stack.pop();
let pop = el;
if (el < this.min) {
pop = this.min;
this._min = 2 * this.min - el;
}
return pop;
}
}
// max version
class MaxStack {
stack: number[] = [];
num: number = 0;
private _max: number;
get max(): number {
if (this.num > 0) {
return this._max;
}
}
push(el: number) {
this.num++;
if (this.num === 1) {
this.stack.push(el);
this._max = el;
return;
}
if (el <= this.max) {
this.stack.push(el);
return;
}
this.stack.push(2 * el - this.max);
this._max = el;
}
pop(): number {
if (this.num === 0) {
return;
}
this.num--;
let el = this.stack.pop();
let pop = el;
if (el > this.max) {
pop = this.max;
this._max = 2 * this.max - el;
}
return pop;
}
}
@Shuumatsu
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment