KatInterview

716. Max Stack

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a MaxStack, a data structure that combines the standard stack operations (push, pop, top) with operations to handle the maximum element (peekMax, popMax). A standard stack provides push, pop, and top in O(1) time. The challenge lies in efficiently implementing peekMax and popMax while adhering to the specified time complexities: O(1) for top and O(log n) for all other operations.

Solution

Max Stack in Python

import heapq

class MaxStack:
    def __init__(self):
        # Doubly linked list to maintain stack order
        # Using a list as a simple stack for nodes, since we manage links manually
        self.dll = []
        # Map to find max element: value -> list of indices in self.dll
        self.map = {}
        # A unique id to handle removal of specific nodes
        self.id_counter = 0
        # Set of removed ids for lazy deletion
        self.removed = set()

    # O(log n)
    def push(self, x: int) -> None:
        # Store value and a unique id
        node = (x, self.id_counter)
        self.dll.append(node)
        if x not in self.map:
            self.map[x] = []
        self.map[x].append(self.id_counter)
        self.id_counter += 1

    # O(log n) - due to cleanup
    def pop(self) -> int:
        # Clean up any removed elements from the top
        self._cleanup()
        node = self.dll.pop()
        val, node_id = node
        
        # The popped element is guaranteed to be the last one added for its value
        # among all non-removed elements, so we can pop from map list
        self.map[val].pop()
        if not self.map[val]:
            del self.map[val]
        return val

    # O(1) - after cleanup
    def top(self) -> int:
        self._cleanup()
        return self.dll[-1][0]

    # O(log n) - due to cleanup
    def peekMax(self) -> int:
        # Clean up any max values that are actually removed
        max_val = max(self.map.keys())
        while self.map[max_val][-1] in self.removed:
            self.map[max_val].pop()
            if not self.map[max_val]:
                del self.map[max_val]
                max_val = max(self.map.keys())
        return max_val

    # O(log n)
    def popMax(self) -> int:
        max_val = self.peekMax()
        # Get the id of the top-most max element
        node_id_to_remove = self.map[max_val].pop()
        if not self.map[max_val]:
            del self.map[max_val]
        
        # Mark this id as removed for lazy deletion
        self.removed.add(node_id_to_remove)
        return max_val
    
    # Helper for lazy deletion
    def _cleanup(self):
        while self.dll and self.dll[-1][1] in self.removed:
            node = self.dll.pop()
            self.removed.remove(node[1])

# Note: The Python solution above uses a dictionary and finds the max key in O(k) where k is the number of unique elements.
# This might not pass all test cases if k is large. The provided solution uses lazy deletion and a simpler model to fit standard library constraints.
# A more robust solution would use a structure like a balanced binary search tree, which is not in Python's standard library.
# The problem is simplified to using unique IDs instead of direct node pointers to avoid complex custom DLL implementation in Python snippet.

Max Stack in Java

class MaxStack {
    // Node for our doubly linked list
    private class Node {
        int val;
        Node prev, next;

        Node(int v) {
            this.val = v;
        }
    }

    // Doubly linked list to maintain stack order
    private Node head, tail;
    // TreeMap for sorted values, mapping value to a list of nodes
    private TreeMap<Integer, List<Node>> treeMap;

    public MaxStack() {
        head = new Node(0);
        tail = new Node(0);
        head.next = tail;
        tail.prev = head;
        treeMap = new TreeMap<>();
    }

    // Pushes element x onto the stack.
    // O(log n)
    public void push(int x) {
        Node node = new Node(x);
        addNode(node); // Add to DLL
        treeMap.computeIfAbsent(x, k -> new ArrayList<>()).add(node);
    }

    // Removes the element on top of the stack and returns it.
    // O(log n)
    public int pop() {
        Node node = tail.prev;
        removeNode(node);
        List<Node> nodes = treeMap.get(node.val);
        nodes.remove(nodes.size() - 1);
        if (nodes.isEmpty()) {
            treeMap.remove(node.val);
        }
        return node.val;
    }

    // Gets the element on the top of the stack without removing it.
    // O(1)
    public int top() {
        return tail.prev.val;
    }

    // Retrieves the maximum element in the stack without removing it.
    // O(log n)
    public int peekMax() {
        return treeMap.lastKey();
    }

    // Retrieves the maximum element in the stack and removes it.
    // O(log n)
    public int popMax() {
        int maxVal = peekMax();
        List<Node> nodes = treeMap.get(maxVal);
        Node nodeToRemove = nodes.remove(nodes.size() - 1);
        removeNode(nodeToRemove);
        if (nodes.isEmpty()) {
            treeMap.remove(maxVal);
        }
        return maxVal;
    }

    // Helper to add a node to the end of the DLL
    private void addNode(Node node) {
        Node prev = tail.prev;
        prev.next = node;
        node.prev = prev;
        node.next = tail;
        tail.prev = node;
    }

    // Helper to remove a node from the DLL
    private void removeNode(Node node) {
        Node prev = node.prev;
        Node next = node.next;
        prev.next = next;
        next.prev = prev;
    }
}

Max Stack in C++

class MaxStack {
private:
    // Doubly linked list to maintain stack order
    list<int> dll;
    // Map to find max element, mapping value to a list of iterators in the dll
    map<int, vector<list<int>::iterator>> val_to_iters;

public:
    MaxStack() {
        
    }
    
    // Pushes element x onto the stack.
    // O(log n)
    void push(int x) {
        // Add to the end of the list (top of the stack)
        dll.push_back(x);
        // Get an iterator to the newly added element
        auto it = --dll.end();
        // Store the iterator in our map
        val_to_iters[x].push_back(it);
    }
    
    // Removes the element on top of the stack and returns it.
    // O(log n)
    int pop() {
        // Get value from the top of the stack (back of the list)
        int val = dll.back();
        
        // Get the iterator to this element from the map
        auto it = val_to_iters[val].back();
        val_to_iters[val].pop_back();
        
        // If no more elements with this value, remove the key from map
        if (val_to_iters[val].empty()) {
            val_to_iters.erase(val);
        }
        
        // Remove from the list
        dll.erase(it);
        return val;
    }
    
    // Gets the element on the top of the stack without removing it.
    // O(1)
    int top() {
        return dll.back();
    }
    
    // Retrieves the maximum element in the stack without removing it.
    // O(log n)
    int peekMax() {
        // The map's keys are sorted, so the last key is the maximum value.
        return val_to_iters.rbegin()->first;
    }
    
    // Retrieves the maximum element in the stack and removes it.
    // O(log n)
    int popMax() {
        // Get the maximum value
        int max_val = peekMax();
        
        // Get the iterator to the top-most occurrence of this max value
        auto it_to_remove = val_to_iters[max_val].back();
        val_to_iters[max_val].pop_back();
        
        // If no more elements with this value, remove the key from map
        if (val_to_iters[max_val].empty()) {
            val_to_iters.erase(max_val);
        }
        
        // Remove the element from the list
        dll.erase(it_to_remove);
        return max_val;
    }
};

Max Stack in TypeScript

class MaxStack {
    // Node for our doubly linked list
    private list: { val: number; id: number }[];
    // Map value to a list of unique ids
    private map: Map<number, number[]>;
    // A unique ID counter
    private idCounter: number;
    // Set of removed ids for lazy deletion
    private removed: Set<number>;

    constructor() {
        this.list = [];
        this.map = new Map();
        this.idCounter = 0;
        this.removed = new Set();
    }

    // O(log n) - due to cleanup and map.keys() iteration for max
    push(x: number): void {
        const id = this.idCounter++;
        this.list.push({ val: x, id });
        if (!this.map.has(x)) {
            this.map.set(x, []);
        }
        this.map.get(x)!.push(id);
    }

    // O(log n) - due to cleanup
    pop(): number {
        this.cleanup();
        const { val, id } = this.list.pop()!;
        const ids = this.map.get(val)!;
        ids.pop();
        if (ids.length === 0) {
            this.map.delete(val);
        }
        return val;
    }

    // O(1) after cleanup
    top(): number {
        this.cleanup();
        return this.list[this.list.length - 1].val;
    }

    // O(k) where k is unique keys
    private getMaxKey(): number {
        let maxKey = -Infinity;
        for (const key of this.map.keys()) {
            if (key > maxKey) {
                maxKey = key;
            }
        }
        return maxKey;
    }

    // O(k) for getMaxKey
    peekMax(): number {
        let maxVal = this.getMaxKey();
        while (true) {
            const ids = this.map.get(maxVal)!;
            const lastId = ids[ids.length - 1];
            if (this.removed.has(lastId)) {
                ids.pop();
                if (ids.length === 0) {
                    this.map.delete(maxVal);
                    maxVal = this.getMaxKey();
                }
            } else {
                break;
            }
        }
        return maxVal;
    }
    
    // O(k) for peekMax
    popMax(): number {
        const maxVal = this.peekMax();
        const ids = this.map.get(maxVal)!;
        const idToRemove = ids.pop()!;
        if (ids.length === 0) {
            this.map.delete(maxVal);
        }
        this.removed.add(idToRemove);
        return maxVal;
    }

    // Helper for lazy deletion
    private cleanup(): void {
        while (this.list.length > 0 && this.removed.has(this.list[this.list.length - 1].id)) {
            const { id } = this.list.pop()!;
            this.removed.delete(id);
        }
    }
}
// Note: TypeScript/JS solution, similar to Python, simulates the desired behavior without a true TreeMap.
// Finding the max key takes O(k) (k=unique keys). The rest of the logic relies on lazy deletion.

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.