-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackWithMin.js
More file actions
34 lines (30 loc) · 816 Bytes
/
stackWithMin.js
File metadata and controls
34 lines (30 loc) · 816 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
// Create a Stack class which also has a function `min` that returns
// the minimum element. Functions `push`, `pop`, and `min` should all
// operate in O(1) time.
class Stack {
constructor () {
this.stackLength = 0
this.stack = []
this.minsLength = 0
this.minsIndices = []
}
min () {
return this.stack[this.minsIndices[this.minsLength - 1]]
}
push (val) {
this.stack[this.stackLength] = val
if (val < this.min() || this.stackLength === 0) {
this.minsIndices[this.minsLength] = this.stackLength
this.minsLength += 1
}
this.stackLength += 1
}
pop () {
const val = this.stack[this.stackLength - 1]
this.stackLength -= 1
if (this.minsIndices[this.minsLength - 1] === this.stackLength) {
this.minsLength -= 1
}
return val
}
}