/
solution.ts
46 lines (38 loc) · 1.13 KB
/
solution.ts
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
45
46
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Stack #Design
// #Data_Structure_II_Day_14_Stack_Queue #Programming_Skills_II_Day_18 #Level_2_Day_16_Design
// #Udemy_Design #Big_O_Time_O(1)_Space_O(N) #2023_10_08_Time_84_ms_(92.72%)_Space_51.8_MB_(30.46%)
class MinStack {
stack: number[]
minStack: number[]
constructor() {
this.stack = []
this.minStack = []
}
push(val: number): void {
this.stack.push(val)
if (this.minStack.length === 0 || this.minStack[this.minStack.length - 1] >= val) {
this.minStack.push(val)
}
}
pop(): void {
const popValue = this.stack.pop()
if (popValue === this.minStack[this.minStack.length - 1]) {
this.minStack.pop()
}
}
top(): number {
return this.stack[this.stack.length - 1]
}
getMin(): number {
return this.minStack[this.minStack.length - 1]
}
}
/*
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(val)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
export { MinStack }