Max Stack
Build a stack that can also report its largest value and remove it from wherever it sits.
Design a stack class with five methods. push(x)xpop()top()peekMax()popMax()popMax()push
Example 1
Output: top() = 5, popMax() = 5, top() = 1, peekMax() = 5, pop() = 1, top() = 5
Explanation: popMax removes the upper 5, leaving [5, 1] from bottom to top.
The Idea
A stack works like a pile of plates: you put a plate on top, and you take plates off the top. pushpoptop
Follow Example 1. After push(5)push(1)push(5)popMax()top()
Answering peekMax()peekMax()
But popMax()push(7)push(2)push(4)popMax()
So the stack needs two views of the same values at once: in stack order, for pushpoptop
Two structures fit these two views. A doubly linked list is a chain of nodes in which each node points to the next node and to the previous one. A TreeMap
The picture shows Example 1 after the three pushes. It calls the two 5s 5a, pushed first, and 5b, pushed last, to tell them apart. The top row, labelled "the stack, bottom to top", is the doubly linked list 5a, 1, 5b. The bottom row, labelled "the map, smallest value to largest", keeps value 1 with node 1, and value 5 with nodes 5b and 5a, newest first. The dashed arrows show which node each map entry points to.
Now popMax()
So the values are stored once, as nodes, and two structures point at them: the list remembers the order, and the map remembers the sizes.
Solution Approach
First, a quick look at the simple way and why it is slow. Then four things need settling: how a node leaves the list, how the map stores repeated values, how the list and the map stay in step, and when a value leaves the map.
The simple way
Why not keep the values in an ArrayListpushpoptoppeekMax()popMax()
Removing a node from the list
How does a node leave the middle of the list? Its previous node is pointed at its next node, and its next node is pointed back at its previous one. Nothing else moves. To make that work for the bottom and top nodes too, the list has two dummy nodes, headtailtail
Repeated values in the map
What does the map keep for a value that is on the stack twice, like 5 in the example? Each key maps to a small stack of its nodes, an ArrayDequepopMax()
Keeping the list and the map in step
Which node does each removal touch? pop()tailpopMax()
When a value leaves the map
What happens when the last copy of a value is removed? Its small stack is empty, so its key is removed from the map as well. That keeps every key a value that is really on the stack, so the largest key is always the true largest value.
Java Solution
The class has these parts, one for each piece of the approach:
: one value on the stack, with links to the node below it (Node ) and above it (prev ).next andhead : the sentinels. The constructor links them to each other, so an empty stack is just these two.tail : thebyValue from each value to its nodes, newest first.TreeMap : links a new node in just belowpush and adds it to the front of its value's nodes intail .byValue andpop : pick the node to remove, from the list or from the map, then take it out of both.popMax andtop : readpeekMax andtail.prev , the largest key.byValue.lastKey() : the two-line removal from the list.unlink : takes the newest node of a value and drops the key when no nodes are left.removeFromMap : prints the stack from bottom to top, fortoString .main
The main
import java.util.ArrayDeque;
import java.util.StringJoiner;
import java.util.TreeMap;
public class MaxStack {
private static class Node {
final int val;
Node prev;
Node next;
Node(int val) {
this.val = val;
}
}
private final Node head = new Node(0); // sentinel below the bottom
private final Node tail = new Node(0); // sentinel above the top
// value -> the nodes holding that value, newest first
private final TreeMap<Integer, ArrayDeque<Node>> byValue = new TreeMap<>();
public MaxStack() {
head.next = tail;
tail.prev = head;
}
public void push(int x) {
Node node = new Node(x);
node.prev = tail.prev; // link the node in just below tail
node.next = tail;
tail.prev.next = node;
tail.prev = node;
byValue.computeIfAbsent(x, k -> new ArrayDeque<>()).push(node);
}
public int pop() {
Node node = tail.prev; // the top node
unlink(node);
removeFromMap(node.val); // it is also the newest node for its value
return node.val;
}
public int top() {
return tail.prev.val;
}
public int peekMax() {
return byValue.lastKey(); // the largest key
}
public int popMax() {
int max = byValue.lastKey();
Node node = removeFromMap(max); // the copy of max closest to the top
unlink(node);
return max;
}
private void unlink(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private Node removeFromMap(int val) {
ArrayDeque<Node> nodes = byValue.get(val);
Node node = nodes.pop();
if (nodes.isEmpty()) {
byValue.remove(val); // no copies left: drop the key too
}
return node;
}
@Override
public String toString() { // the stack, bottom to top
StringJoiner sj = new StringJoiner(", ", "[", "]");
for (Node n = head.next; n != tail; n = n.next) {
sj.add(String.valueOf(n.val));
}
return sj.toString();
}
public static void main(String[] args) {
MaxStack s = new MaxStack();
s.push(5);
s.push(1);
s.push(5);
System.out.println("after push(5), push(1), push(5): " + s);
System.out.println("top() = " + s.top());
System.out.println("popMax() = " + s.popMax() + ", stack " + s);
System.out.println("top() = " + s.top());
System.out.println("peekMax() = " + s.peekMax());
System.out.println("pop() = " + s.pop() + ", stack " + s);
System.out.println("top() = " + s.top());
MaxStack t = new MaxStack(); // the largest value at the bottom
t.push(7);
t.push(2);
t.push(4);
System.out.println("after push(7), push(2), push(4): " + t);
System.out.println("popMax() = " + t.popMax() + ", stack " + t);
System.out.println("peekMax() = " + t.peekMax() + ", top() = " + t.top());
MaxStack u = new MaxStack(); // the only copy of the max leaves
u.push(3);
u.push(7);
System.out.println("after push(3), push(7): popMax() = " + u.popMax()
+ ", peekMax() = " + u.peekMax());
}
}
Running it prints:
after push(5), push(1), push(5): [5, 1, 5]
top() = 5
popMax() = 5, stack [5, 1]
top() = 1
peekMax() = 5
pop() = 1, stack [5]
top() = 5
after push(7), push(2), push(4): [7, 2, 4]
popMax() = 7, stack [2, 4]
peekMax() = 4, top() = 4
after push(3), push(7): popMax() = 7, peekMax() = 3
Look at the line popMax() = 5, stack [5, 1]top()peekMax()pop()top()
The stack [7, 2, 4]popMax() = 7[2, 4]
The last line depends on removeFromMappeekMax()byValue.remove(val)peekMax() = 7[2, 4]
Complexity
Each method does a fixed amount of linking plus at most a few map calls, so the TreeMap
- Time: O(log n) for
,push ,pop andpeekMax , with n values on the stack. ApopMax keeps its keys in a balanced tree about log n levels deep, and each lookup, insert or removal walks down it once. Linking or unlinking a node changes four links.TreeMap is O(1), because it only readstop .tail.prev - Space: O(n), because every value on the stack has one list node and one entry in its value's small stack, and the map has at most one key per distinct value.
Linking a map to a doubly linked list is also the design of