-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC4P7.java
More file actions
36 lines (28 loc) · 746 Bytes
/
C4P7.java
File metadata and controls
36 lines (28 loc) · 746 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
// Find the Minimum stack with better Space Complexity that C4P6
// Time Complexity O(1)
// Space Complexity O(n) based on where minimum is encountered
import java.util.EmptyStackException;
import java.util.Stack;
public class C4P7 {
Stack <Integer> mainStack = new Stack<Integer>();
Stack <Integer> minStack = new Stack<Integer>();
public void Push(int data) {
mainStack.push(data);
if(minStack.isEmpty())
minStack.push(data);
else {
if(mainStack.peek() < data)
minStack.push(data);
}
}
public int Pop() {
if(!mainStack.isEmpty()) {
if(mainStack.peek() == minStack.peek()) {
minStack.pop();
return mainStack.pop();
}
return mainStack.pop();
}
throw new EmptyStackException();
}
}