-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathMinStack.java
More file actions
44 lines (36 loc) · 992 Bytes
/
MinStack.java
File metadata and controls
44 lines (36 loc) · 992 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
44
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Approach:
// Use two stacks: one to store values and another to track the minimum at each level.
// On every push, store the current minimum so getMin is always O(1).
// On pop, remove from both stacks to keep them in sync.
import java.util.Stack;
class MinStack {
Stack<Integer> st;
Stack<Integer> minSt;
int min;
public MinStack() {
this.st = new Stack<>();
this.minSt = new Stack<>();
this.min = Integer.MAX_VALUE;
minSt.push(min);
}
public void push(int val) {
min = Math.min(val,min);
st.push(val);
minSt.push(min);
}
public void pop() {
st.pop();
minSt.pop();
min = minSt.peek();
}
public int top() {
return st.peek();
}
public int getMin() {
return min;
}
}