The task is taken from leetcode
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
My first solution
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.repo = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (!isNaN(x)) {
this.repo.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
return this.repo.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.repo[this.repo.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
if (this.repo) {
const copy = this.repo.slice(0);
return copy.sort((a,b) => a - b)[0];
}
};
My second solution
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.repo = [];
this.minRepo = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (!isNaN(x)) {
if (!this.minRepo.length || x <= this.minRepo[0]) {
this.minRepo.unshift(x);
}
this.repo.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if (this.repo.pop() === this.minRepo[0]) {
this.minRepo.shift();
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.repo[this.repo.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
if (this.minRepo.length) {
return this.minRepo[0];
}
};
For the second solution I was thinking of adding the numbers not from the back (with push
) but instead from the front (with unshift
). The advantage is that I would need less operation inside the method top (return this.repo[0]
would be sufficient - no need for calculating the last element with this.repo.length - 1
). But I don't whether this would be "weird" and would mean too much "mental mapping" (the function is called push
but I use a shift
inside).