forked from anthonynsimon/java-ds-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinStack.java
More file actions
56 lines (43 loc) · 1.55 KB
/
MinStack.java
File metadata and controls
56 lines (43 loc) · 1.55 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.anthonynsimon.algorithms.stacksqueues;
import com.anthonynsimon.datastructures.Stack;
import java.util.EmptyStackException;
public final class MinStack<T extends Comparable<T>> {
// Keep two stacks, one for the data and one for the current min
// Keeps a history of min elements so we always have O(1) time complexity
// for the push, pop and min methods as we don't have to search for the next
// min every time we pop a data element which is also a min.
private Stack<T> dataStack;
private Stack<T> minStack;
public MinStack() {
this.dataStack = new Stack<>();
this.minStack = new Stack<>();
}
public void push(T item) throws IllegalArgumentException {
if (item == null) {
throw new IllegalArgumentException();
}
dataStack.push(item);
// If the new item is <= to previous min push it to minStack
if (minStack.size() == 0 || item.compareTo(min()) <= 0) {
minStack.push(item);
}
}
public T pop() throws EmptyStackException {
T temp = dataStack.pop();
if (temp == null) {
throw new EmptyStackException();
}
// If the popped data element is the current min element, then
// pop from the minStack to sync them
if (min().compareTo(temp) == 0) {
minStack.pop();
}
return temp;
}
public T min() throws EmptyStackException {
if (minStack.size() == 0) {
throw new EmptyStackException();
}
return minStack.peek();
}
}