Skip to content

Instantly share code, notes, and snippets.

@basekays
Created September 27, 2018 17:48
Show Gist options
  • Select an option

  • Save basekays/898e21566d18e933b0474a036fba3a9b to your computer and use it in GitHub Desktop.

Select an option

Save basekays/898e21566d18e933b0474a036fba3a9b to your computer and use it in GitHub Desktop.
const MinStack = function() {
this.items = [];
this.minValueTracker = [];
};
MinStack.prototype.push = function(x) {
const minValueTrackerLength = this.minValueTracker.length - 1;
const latestMinValue = this.minValueTracker[minValueTrackerLength];
this.items.push(x);
if (!this.minValueTracker.length) {
this.minValueTracker.push(x);
} else {
if (x < latestMinValue) {
this.minValueTracker.push(x);
} else {
this.minValueTracker.push(latestMinValue);
}
}
};
MinStack.prototype.pop = function() {
this.items.pop();
this.minValueTracker.pop();
};
MinStack.prototype.top = function() {
return this.items[this.items.length - 1];
};
MinStack.prototype.getMin = function() {
return this.minValueTracker[this.minValueTracker.length - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment