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) puts x on top, pop() removes and returns the top value, and top() returns the top value without removing it. peekMax() returns the largest value on the stack, and popMax() removes and returns it. If the largest value is on the stack more than once, popMax() removes the copy closest to the top. The methods other than push are only called when the stack is not empty.

Example 1
Input: push(5), push(1), push(5), top(), popMax(), top(), peekMax(), pop(), top()
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.
Solution

The Idea

A stack works like a pile of plates: you put a plate on top, and you take plates off the top. push, pop and top are those moves. This problem adds two more: say which value in the pile is the largest, and pull that value out wherever it sits.

Follow Example 1. After push(5), push(1) and push(5), the stack holds 5, 1, 5 from bottom to top. The largest value is 5, and it is there twice. popMax() takes the 5 closest to the top, so the stack becomes 5, 1, and top() now returns 1.

Answering peekMax() alone is the easy half. In Min Stack, each entry also stores the smallest value at or below it, so the answer always sits on top. Storing the largest value instead would answer peekMax() at once.

But popMax() breaks those stored largest values. After push(7), push(2) and push(4), the largest value, 7, is at the bottom. popMax() has to take it out from under 2 and 4, and the "largest so far" stored with 2 and 4 is 7, which is now wrong for both.

So the stack needs two views of the same values at once: in stack order, for push, pop and top, and in size order, to find the largest. And once the largest is found, how can it leave the middle of the stack without shifting everything above it?

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 is Java's map that keeps its keys sorted, so its largest key is always easy to reach. Look at the picture below.

After push(5), push(1), push(5), the stack is a doubly linked list 5a, 1, 5b from bottom to top. A TreeMap maps value 1 to node 1 and value 5 to nodes 5b and 5a, newest first. popMax takes the largest key, 5, and its newest node, 5b, and unlinks it from the list.

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() asks the map for its largest key, 5, and takes the newest node under it, 5b. That node knows both its neighbours, so it can leave the list straight away, without a walk down from the top. Here 5b happens to be on top. With 7, 2, 4, the node would be 7 at the bottom, and it leaves the same way.

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 ArrayList, with the top at the end? push, pop and top are quick, but peekMax() must look at every value, and popMax() must also shift every value above the one it removes. With n values on the stack, each of those calls takes about n steps.

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, head below the bottom and tail above the top. Dummy end nodes like these are called sentinels. Every real node then has two neighbours, and the top value is always the node just below tail.

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 ArrayDeque (Java's double-ended queue class, used here as a stack), with the newest node in front. A node pushed later sits higher in the list, so the front node is the copy closest to the top, which is the one popMax() must take.

Keeping the list and the map in step

Which node does each removal touch? pop() unlinks the node below tail and then takes the front node from its value's small stack. That front node is the same node: any newer node with the same value would sit above it, and nothing sits above the top. popMax() works the other way round. It asks the map for the largest key, takes the front node for that key, and unlinks it from the list.

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:

  • Node: one value on the stack, with links to the node below it (prev) and above it (next).
  • head and tail: the sentinels. The constructor links them to each other, so an empty stack is just these two.
  • byValue: the TreeMap from each value to its nodes, newest first.
  • push: links a new node in just below tail and adds it to the front of its value's nodes in byValue.
  • pop and popMax: pick the node to remove, from the list or from the map, then take it out of both.
  • top and peekMax: read tail.prev and byValue.lastKey(), the largest key.
  • unlink: the two-line removal from the list. removeFromMap: takes the newest node of a value and drops the key when no nodes are left.
  • toString: prints the stack from bottom to top, for main.

The main method runs Example 1, then removes the largest value when it sits at the bottom under 2 and 4, and when it is the only copy of its value.

Java
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:

Output
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]. Of the two 5s, the upper one left, which is why the next top() prints 1. The rest of Example 1 matches the expected output: peekMax() still finds the lower 5, and after pop() removes 1, top() is 5 again.

The stack [7, 2, 4] shows a removal from the bottom. popMax() = 7 leaves [2, 4] in their old order, and the largest value is now 4.

The last line depends on removeFromMap dropping a key once its nodes are gone. After 7 leaves, peekMax() returns 3. With the line byValue.remove(val) commented out, the same program prints peekMax() = 7 on that line and on the [2, 4] line, a value no longer on either stack.

Complexity

Each method does a fixed amount of linking plus at most a few map calls, so the TreeMap sets the cost.

  • Time: O(log n) for push, pop, peekMax and popMax, with n values on the stack. A TreeMap 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. top is O(1), because it only reads 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 LRU Cache.