-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathMinStackUsingSingleStack.java
65 lines (59 loc) · 1.6 KB
/
MinStackUsingSingleStack.java
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
57
58
59
60
61
62
63
64
65
package com.thealgorithms.stacks;
import java.util.EmptyStackException;
import java.util.Stack;
/**
* Min-Stack implementation using a single stack.
*
* This stack supports push, pop, and retrieving the minimum element
* in constant time (O(1)) using a modified approach where the stack
* stores both the element and the minimum value so far.
*
* @author Hardvan
*/
public class MinStackUsingSingleStack {
private final Stack<long[]> stack = new Stack<>();
/**
* Pushes a new value onto the stack.
* Each entry stores both the value and the minimum value so far.
*
* @param value The value to be pushed onto the stack.
*/
public void push(int value) {
if (stack.isEmpty()) {
stack.push(new long[] {value, value});
} else {
long minSoFar = Math.min(value, stack.peek()[1]);
stack.push(new long[] {value, minSoFar});
}
}
/**
* Removes the top element from the stack.
*/
public void pop() {
if (!stack.isEmpty()) {
stack.pop();
}
}
/**
* Retrieves the top element from the stack.
*
* @return The top element of the stack.
*/
public int top() {
if (!stack.isEmpty()) {
return (int) stack.peek()[0];
}
throw new EmptyStackException();
}
/**
* Retrieves the minimum element in the stack.
*
* @return The minimum element so far.
*/
public int getMin() {
if (!stack.isEmpty()) {
return (int) stack.peek()[1];
}
throw new EmptyStackException();
}
}