-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin-stack.ts
More file actions
42 lines (38 loc) · 1.07 KB
/
Copy pathmin-stack.ts
File metadata and controls
42 lines (38 loc) · 1.07 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
/**
* 155. Min Stack (Medium)
* Link: https://leetcode.com/problems/min-stack/
*
* Design a stack that supports push, pop, top, and retrieving the minimum
* element — all in O(1).
*
* Example:
* push(-2); push(0); push(-3);
* getMin() -> -3; pop(); top() -> 0; getMin() -> -2
*
* Approach:
* Alongside the main stack keep a parallel "min stack" whose top is always the
* minimum of the current elements. On push, store min(value, currentMin); on
* pop, remove from both. Every operation is O(1).
*
* Time: O(1) per operation.
* Space: O(n) — the auxiliary min stack.
*/
export class MinStack {
private readonly stack: number[] = [];
private readonly mins: number[] = [];
push(val: number): void {
this.stack.push(val);
const min = this.mins.length === 0 ? val : Math.min(val, this.mins[this.mins.length - 1]);
this.mins.push(min);
}
pop(): void {
this.stack.pop();
this.mins.pop();
}
top(): number {
return this.stack[this.stack.length - 1];
}
getMin(): number {
return this.mins[this.mins.length - 1];
}
}