How to implement a stack with an O(1) min method

Here is one way to implement a stack with a min method which returns the smallest item in the stack (assuming the stack is composed only of numbers). push, pop, and min should be O(1) time.

StackMinTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function StackMin() {
this.top = null;
this.size = 0;
this.minStack = [];
}
function Node(data) {
this.data = data;
this.next = null;
}
StackMin.prototype.push = function(data) {
if (!this.minStack.length) {
this.minStack.push(data);
} else if (data < this.minStack[this.minStack.length-1]) {
this.minStack.push(data);
}
const node = new Node(data);
node.next = this.top;
this.top = node;
this.size++;
};
StackMin.prototype.pop = function() {
if (this.top === null) return;
const data = this.top.data;
if (this.minStack[this.minStack.length-1] === this.top.data) this.minStack.pop();
this.top = this.top.next;
this.size = Math.max(0, this.size - 1);
return data;
};
StackMin.prototype.peek = function() {
if (!this.top) return;
return this.top.data;
};
StackMin.prototype.isEmpty = function() {
return this.size === 0 && !this.top;
};
StackMin.prototype.min = function() {
return this.minStack[this.minStack.length-1];
};

Tests can be found at REPL.it