-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0155-min-stack.js
More file actions
43 lines (37 loc) · 1.12 KB
/
0155-min-stack.js
File metadata and controls
43 lines (37 loc) · 1.12 KB
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
/**
* Min Stack
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var MinStack = function () {
this.elementStorage = [];
};
MinStack.prototype.push = function (val) {
let pushedItemValue = val;
let currentOverallMinimum;
if (this.elementStorage.length === 0) {
currentOverallMinimum = pushedItemValue;
} else {
let lastElementData = this.elementStorage[this.elementStorage.length - 1];
let previousMinTracked = lastElementData.minimumValueAtAddition;
currentOverallMinimum = Math.min(pushedItemValue, previousMinTracked);
}
this.elementStorage.push({
actualValue: pushedItemValue,
minimumValueAtAddition: currentOverallMinimum,
});
};
MinStack.prototype.pop = function () {
this.elementStorage.pop();
};
MinStack.prototype.top = function () {
let topStackEntry = this.elementStorage[this.elementStorage.length - 1];
return topStackEntry.actualValue;
};
MinStack.prototype.getMin = function () {
if (this.elementStorage.length === 0) {
return 0;
}
let currentMinEntry = this.elementStorage[this.elementStorage.length - 1];
return currentMinEntry.minimumValueAtAddition;
};