-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin-stack.js
More file actions
43 lines (38 loc) · 726 Bytes
/
min-stack.js
File metadata and controls
43 lines (38 loc) · 726 Bytes
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
/**
* Stack that supports push, pop, top, and
* retrieving the min element in constant time.
*
* @author Jagdeep Singh
* @date 2019-09-02
* @export
* @class MinStack
*/
export default class MinStack {
constructor() {
this.min = [];
this.stack = [];
}
push(x) {
this.stack.push(x);
const curMin = this.getMin();
if (curMin !== undefined) {
this.min.push(Math.min(x, curMin));
} else {
this.min.push(x);
}
}
pop() {
this.stack.pop();
this.min.pop();
}
top() {
if (this.stack.length > 0) {
return this.stack[this.stack.length - 1];
}
}
getMin() {
if (this.min.length > 0) {
return this.min[this.min.length - 1];
}
}
}