Implementing a stack that retrieves the minimum element in constant time requires a supplementary tracking mechanism rather than relying on a linear scan during query operations. The optimal architecture utilizes two parallel data structures operating in lockstep. The primary collection archives every inserted payload, while the secondary collection mirrors the state history specifically for baseline minimization.
During an insertion event, the algorithm evaluates the incoming integer against the current tracked threshold. If the secondary structure is vacant or the new value meets or exceeds the threshold condition, the value itself is recorded. Otherwise, the existing baseline value is duplicated into the secondary structure. This redundancy ensures that every push operation corresponds to a synchronized entry in both collections, preserving O(1) access latency regardless of dataset size.
Deletion operations simultaneously retract the topmost nodes from both collections. Accessing the most recent element or querying the current minimum simply inspects the leading node of the primary or secondary structure, respectively. This design guarantees deterministic perfomrance for all core stack operations.
import java.util.ArrayDeque;
import java.util.Scanner;
public class MinimumTrackingStack {
private final ArrayDeque<Integer> primaryStorage = new ArrayDeque<>();
private final ArrayDeque<Integer> baselineHistory = new ArrayDeque<>();
public MinimumTrackingStack() {}
public void insert(int payload) {
primaryStorage.push(payload);
int currentThreshold = baselineHistory.isEmpty() ? Integer.MAX_VALUE : baselineHistory.peek();
if (payload <= currentThreshold) {
baselineHistory.push(payload);
} else {
baselineHistory.push(currentThreshold);
}
}
public void removeHighest() {
primaryStorage.pop();
baselineHistory.pop();
}
public int inspectPeek() {
return primaryStorage.peek();
}
public int fetchLowest() {
return baselineHistory.peek();
}
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
MinimumTrackingStack tracker = new MinimumTrackingStack();
while (inputReader.hasNext()) {
String directive = inputReader.next();
switch (directive) {
case "reset" -> tracker = new MinimumTrackingStack();
case "insert" -> tracker.insert(inputReader.nextInt());
case "remove" -> tracker.removeHighest();
case "checkTop" -> System.out.println(tracker.inspectPeek());
case "checkMin" -> System.out.println(tracker.fetchLowest());
default -> System.err.println("Unsupported directive: " + directive);
}
}
inputReader.close();
}
}