Max-Tracking Stack

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build a last-in, first-out (LIFO) integer container that supports fast maximum queries and targeted maximum eviction across five commands:

  • push(x) — Insert integer x as the newest active entry and record None.
  • pop() — Evict the newest active entry and output its value.
  • top() — Read and output the newest active entry while leaving the container unchanged.
  • peekMax() — Read and output the largest integer among all active entries while leaving the container unchanged.
  • popMax() — Evict and output the largest integer among all active entries; when two or more active entries tie for that maximum, evict whichever tied copy was inserted most recently.

Your function maximum_tracking_stack(operations, arguments) receives two equal-length lists: - operations[i] names the i-th command ("push", "pop", "top", "peekMax", or "popMax"). - arguments[i] holds [x] for "push" commands and [] for all other commands.

Replay every command in order starting from an empty container, and return the list of per-command outputs (None for "push", and the returned integer otherwise). Every query or eviction command ("pop", "top", "peekMax", "popMax") is guaranteed to run when at least one active entry exists.

Examples

Example 1

Input:
  operations = ["push", "push", "push", "peekMax", "popMax", "top", "pop", "peekMax"]
  arguments  = [[8], [3], [8], [], [], [], [], []]
Output:
  [None, None, None, 8, 8, 3, 3, 8]

Walk-through: 1. Inserting 8, 3, and 8 builds [8, 3, 8] from oldest to newest. 2. peekMax() reports 8 without mutating the container. 3. popMax() finds two 8s and evicts the newer copy, leaving [8, 3] and returning 8. 4. top() observes 3, and pop() evicts 3, leaving [8]. 5. peekMax() reports the surviving 8.

Example 2

Input:
  operations = ["push", "push", "push", "push", "popMax", "top", "pop", "peekMax"]
  arguments  = [[-4], [6], [-1], [2], [], [], [], []]
Output:
  [None, None, None, None, 6, 2, 2, -1]

Walk-through: 1. Inserting -4, 6, -1, and 2 produces [-4, 6, -1, 2] from oldest to newest. 2. popMax() removes 6 from the interior, leaving [-4, -1, 2] and returning 6. 3. top() reads 2, and pop() removes 2, leaving [-4, -1]. 4. peekMax() returns -1 because -1 > -4.

Constraints

  • 1 <= len(operations) == len(arguments) <= 2 * 10^5
  • -10^9 <= x <= 10^9 for every "push" value x
  • Every "pop", "top", "peekMax", and "popMax" call happens on a non-empty container.

Step-by-step walkthrough

  1. Understand the five operations and tie-breaker

    We need a LIFO integer container supporting five commands:

    • push(x): insert integer x as the newest item (producing None in the output list).
    • pop() and top(): evict or read the most recently inserted live item.
    • peekMax(): read the largest live integer without modifying the container.
    • popMax(): evict and return the largest live integer — and whenever duplicates tie for that maximum, evict whichever tied copy was inserted latest (nearest the LIFO top).
    Push 8, then 3, then 8:
      stack (bottom -> top):  [ 8(older),  3,  8(newer) ]
                                               ^^^^^^^^
                                         popMax() must remove THIS 8,
                                         leaving [ 8(older), 3 ] with top() == 3!
    
  2. Why a plain list or the classic two-stack trick is too slow

    If you already know "Min Stack", your first instinct is keeping a second stack of running maximums alongside the main stack. That answers peekMax() in O(1) time, until popMax() is called:

    Push 100000, 99999, ..., 2, 1 (strictly decreasing):
      stack (bottom -> top): [100000, 99999, ..., 2, 1]
                               ^^^^^^
                         max is buried at the very bottom!
    
    With two stacks (or a plain list):
      popMax() must pop 99,999 items into a temp buffer, drop 100000, and push 99,999 items back!
      100,000 pushes + 100,000 popMax calls => ~5 * 10^9 operations (times out).
    

    To make popMax fast even when the maximum sits at the bottom, we need a second view ordered by value, plus a way to avoid O(n) middle-of-list deletions.

  3. Core idea: pair a stack with a heap using lazy deletion

    Every pushed element gets a unique, monotonically increasing integer push_id (0, 1, 2, ...) and is placed into two structures at the same time:

    1. self.stack: a plain list of (value, push_id) pairs for top() and pop().
    2. self.max_heap: Python's heapq min-heap storing (-value, -push_id) tuples for peekMax() and popMax().

    Why (-value, -push_id)? Negating value puts the largest value at max_heap[0]. When two items share the same value, Python compares the second tuple element -push_id: a larger push_id (pushed later, closer to the stack top) becomes a more negative -push_id, so it wins the min-heap tie-breaker!

    Push 8 (id=0) -> heap entry (-8,  0)
    Push 3 (id=1) -> heap entry (-3, -1)
    Push 8 (id=2) -> heap entry (-8, -2)   <-- (-8, -2) < (-8, 0), so id=2 sits at max_heap[0]!
    

    When popMax() removes (8, 2) from max_heap, we do not search self.stack to delete it. Instead, we record 2 in a hash set self.removed_ids (lazy deletion). Stale entries sit harmlessly inside the other structure until they eventually reach stack[-1] or max_heap[0], where a tiny while loop pops and discards them on sight. Because each push_id enters each structure once and is discarded at most once, cleanup stays fast across any sequence of calls.

  4. Implement `push` and the two lazy-cleanup helpers

    Why track deletions by push_id in a set instead of counting values like removed_count[8] += 1? Suppose we run push(8), push(3), popMax(), push(8). The first 8 (id=0) was removed, and a brand-new 8 (id=2) is now on top of the stack. A value counter would mistakenly treat the new 8 on top as deleted! Unique push_id integers never confuse two copies of the same number.

    from typing import List, Set, Tuple
    import heapq
    
    
    class MaxStack:
        def __init__(self) -> None:
            # stack: list of (value, push_id) pairs in LIFO order, e.g. [(8, 0), (3, 1), (8, 2)]
            self.stack: List[Tuple[int, int]] = []
            # max_heap: min-heap of (-value, -push_id) tuples so max_heap[0] has the largest value,
            # breaking ties toward the largest push_id (the copy closest to the top of the stack).
            self.max_heap: List[Tuple[int, int]] = []
            # removed_ids: push_ids already popped via the other view; skipped lazily on read
            self.removed_ids: Set[int] = set()
            # next_id: monotonically increasing unique ID assigned to each pushed item
            self.next_id = 0
    
        def push(self, x: int) -> None:
            push_id = self.next_id
            self.next_id += 1
            self.stack.append((x, push_id))
            heapq.heappush(self.max_heap, (-x, -push_id))
    
        def _prune_stack_top(self) -> None:
            """Discard stale entries at the stack top that were earlier removed by pop_max."""
            while self.stack and self.stack[-1][1] in self.removed_ids:
                self.stack.pop()
    
        def _prune_heap_top(self) -> None:
            """Discard stale entries at the heap root that were earlier removed by pop."""
            while self.max_heap and (-self.max_heap[0][1]) in self.removed_ids:
                heapq.heappop(self.max_heap)
    
  5. Implement `pop`, `top`, `peek_max`, and `pop_max`

    Every read or removal operation calls the matching _prune_* helper first, guaranteeing that stack[-1] (for top/pop) or max_heap[0] (for peek_max/pop_max) belongs to a live element:

    • pop() prunes stack, pops (value, push_id), adds push_id to removed_ids, and returns value.
    • top() prunes stack and returns stack[-1][0].
    • peek_max() prunes max_heap and returns -max_heap[0][0].
    • pop_max() prunes max_heap, pops (neg_value, neg_push_id), adds -neg_push_id to removed_ids, and returns -neg_value.
        def pop(self) -> int:
            self._prune_stack_top()
            value, push_id = self.stack.pop()
            # Mark push_id deleted so max_heap will skip its stale copy when it reaches max_heap[0].
            self.removed_ids.add(push_id)
            return value
    
        def top(self) -> int:
            self._prune_stack_top()
            value, _ = self.stack[-1]
            return value
    
        def peek_max(self) -> int:
            self._prune_heap_top()
            neg_value, _ = self.max_heap[0]
            return -neg_value
    
        def pop_max(self) -> int:
            self._prune_heap_top()
            neg_value, neg_push_id = heapq.heappop(self.max_heap)
            push_id = -neg_push_id
            # Mark push_id deleted so stack will skip its stale copy when it reaches stack[-1].
            self.removed_ids.add(push_id)
            return -neg_value
    
  6. Trace Example 1 step by step

    Let's trace push(8), push(3), push(8), peekMax(), popMax(), top(), pop(), peekMax():

    Call      | stack (bottom->top)           | max_heap root | removed_ids | Return
    ----------+-------------------------------+---------------+-------------+-------
    push(8)   | [(8,0)]                       | (-8, 0)       | {}          | None
    push(3)   | [(8,0), (3,1)]                | (-8, 0)       | {}          | None
    push(8)   | [(8,0), (3,1), (8,2)]         | (-8,-2)       | {}          | None
    peekMax() | [(8,0), (3,1), (8,2)]         | (-8,-2)       | {}          | 8
    popMax()  | [(8,0), (3,1), (8,2)*]        | (-8, 0)       | {2}         | 8   (id=2 popped from heap)
    top()     | prune (8,2)* -> [(8,0),(3,1)] | (-8, 0)       | {2}         | 3
    pop()     | [(8,0)]                       | (-8, 0)       | {1, 2}      | 3   (id=1 popped from stack)
    peekMax() | [(8,0)]                       | (-8, 0) live! | {1, 2}      | 8   ((-3,-1)* stays buried)
    
    (* = stale entry already in removed_ids, ignored until it surfaces)
    
  7. Complete solution

    Finally, maximum_tracking_stack dispatches each (op, args) pair from the input lists to MaxStack and collects the returned values.

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    class MaxStack:
        """Stack supporting O(log n) amortized push/peekMax/popMax and O(1) amortized top/pop."""
    
        def __init__(self) -> None:
            # stack: list of (value, push_id) pairs in LIFO order, e.g. [(8, 0), (3, 1), (8, 2)]
            self.stack: List[Tuple[int, int]] = []
            # max_heap: min-heap of (-value, -push_id) tuples so max_heap[0] has the largest value,
            # breaking ties toward the largest push_id (the copy closest to the top of the stack).
            self.max_heap: List[Tuple[int, int]] = []
            # removed_ids: push_ids already popped via the other view; skipped lazily on read
            self.removed_ids: Set[int] = set()
            # next_id: monotonically increasing unique ID assigned to each pushed item
            self.next_id = 0
    
        def push(self, x: int) -> None:
            push_id = self.next_id
            self.next_id += 1
            self.stack.append((x, push_id))
            heapq.heappush(self.max_heap, (-x, -push_id))
    
        def _prune_stack_top(self) -> None:
            """Discard stale entries at the stack top that were earlier removed by pop_max."""
            while self.stack and self.stack[-1][1] in self.removed_ids:
                self.stack.pop()
    
        def _prune_heap_top(self) -> None:
            """Discard stale entries at the heap root that were earlier removed by pop."""
            while self.max_heap and (-self.max_heap[0][1]) in self.removed_ids:
                heapq.heappop(self.max_heap)
    
        def pop(self) -> int:
            self._prune_stack_top()
            value, push_id = self.stack.pop()
            # Mark push_id deleted so max_heap will skip its stale copy when it reaches max_heap[0].
            self.removed_ids.add(push_id)
            return value
    
        def top(self) -> int:
            self._prune_stack_top()
            value, _ = self.stack[-1]
            return value
    
        def peek_max(self) -> int:
            self._prune_heap_top()
            neg_value, _ = self.max_heap[0]
            return -neg_value
    
        def pop_max(self) -> int:
            self._prune_heap_top()
            neg_value, neg_push_id = heapq.heappop(self.max_heap)
            push_id = -neg_push_id
            # Mark push_id deleted so stack will skip its stale copy when it reaches stack[-1].
            self.removed_ids.add(push_id)
            return -neg_value
    
    
    def maximum_tracking_stack(
        operations: List[str], arguments: List[List[int]]
    ) -> List[Optional[int]]:
        # Replay the operation stream against a single MaxStack instance.
        max_stack = MaxStack()
        results: List[Optional[int]] = []
    
        for op, args in zip(operations, arguments):
            if op == "push":
                max_stack.push(args[0])
                results.append(None)
            elif op == "pop":
                results.append(max_stack.pop())
            elif op == "top":
                results.append(max_stack.top())
            elif op == "peekMax":
                results.append(max_stack.peek_max())
            elif op == "popMax":
                results.append(max_stack.pop_max())
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a coat-check counter that keeps two views of every coat: a physical LIFO (last-in, first-out) rack where the newest coat hangs on the front hook, and a digital scoreboard showing the highest-valued ticket. Every coat gets a unique serial number (push_id = 0, 1, 2, ...). When popMax() claims the highest-valued coat from deep inside the rack, rummaging through thousands of hangers to pull it out immediately would stall the line. Instead, the clerk uses lazy deletion (recording the claimed serial number on a "cancelled IDs" list and leaving the ghost entry inside the other data structure until it naturally reaches the front hook or top of the scoreboard, where it is tossed aside).

Why do simpler designs fall short? A single list makes push, pop, and top O(1), but forces peekMax and popMax to scan all n items in O(n) time. Even the classic two-stack "Min/Max Stack" trick — storing running maximums in a parallel stack — only speeds up peekMax; if you push 100,000, 99,999, ..., 1, the maximum sits at the very bottom, so every popMax() must pop and re-push the entire remaining stack in O(n) time (O(n^2) total). Pairing a stack with a min-heap (a binary tree stored in an array whose smallest tuple sits at index 0 and updates in O(log n) time) gives fast access to both the newest item and the largest item.

Let's trace push(8), push(3), push(8), popMax(), top() from Example 1:

1. push(8) -> id=0: stack=[(8,0)],               max_heap root=(-8, 0)
2. push(3) -> id=1: stack=[(8,0),(3,1)],         max_heap root=(-8, 0)
3. push(8) -> id=2: stack=[(8,0),(3,1),(8,2)],   max_heap root=(-8,-2)  (-2 < 0 wins tie!)
4. popMax()       : pop (-8,-2) from max_heap -> removed_ids={2}, return 8
5. top()          : stack[-1] is (8,2), id 2 is in removed_ids -> pop & skip!
                    new stack[-1] is (3,1), live -> return 3

Complexity

Let n be the total number of push calls so far (so stack and max_heap each hold at most n entries).

  • Time per operation:
    • push: O(log n) worst-case — appending to self.stack is O(1) and pushing onto self.max_heap bubbles up a binary heap of height at most log2(n).
    • top and pop: O(1) amortized (amortized time means the average cost per operation over any worst-case sequence of operations, even if one occasional cleanup loop pops many stale entries at once). Each pushed item is appended to self.stack once and popped from self.stack at most once (either by pop() or by _prune_stack_top()), so k operations perform at most k stack pops in total.
    • peekMax and popMax: O(log n) amortized — each pushed item enters self.max_heap once and is heappop-ed at most once (either by pop_max() or by _prune_heap_top()), charging at most one O(log n) heap removal to each push. Across k total operations, the entire run finishes in O(k log k) time.
  • Space: O(n). self.stack, self.max_heap, and self.removed_ids each store at most one entry per pushed item.

Edge cases

  • Duplicate maximums (push 8, push 3, push 8): Storing -push_id as the second tuple element in (-value, -push_id) makes the most recently pushed copy smallest in the min-heap, removing the copy closest to the top of the stack (Example 1).
  • popMax removes the current top element (push 2, push 9, popMax, top): 9 is popped from max_heap and added to removed_ids; the very next top() or pop() prunes (9, 1) from stack[-1] and exposes 2.
  • Re-pushing a value right after popMax removed an older copy (push 8, push 3, popMax, push 8, top): The new 8 gets a fresh push_id (2), so removed_ids = {0} never accidentally skips the new 8.
  • Negative numbers and interior maximums (Example 2: -4, 6, -1, 2): After popMax() removes 6 and pop() removes 2, negating -4 and -1 stores +4 and +1 in the min-heap, putting +1 (-1) at max_heap[0] ahead of +4 (-4). (Python arbitrary-precision int values never overflow on -x, unlike 32-bit INT_MIN in C++/Java.)
  • Emptying the stack completely and pushing again: next_id keeps incrementing, so old IDs in removed_ids never collide with future pushes.

Common mistakes

  • Pushing (-value, push_id) instead of (-value, -push_id): In a min-heap, (-8, 0) < (-8, 2), which pops the oldest (bottom-most) 8 instead of the copy closest to the top!
  • Tracking lazy deletions by value count (Counter) instead of unique push_id: Fails immediately when the same number is pushed again after popMax removed an earlier copy deeper in the stack.
  • Forgetting _prune_stack_top() inside top() or _prune_heap_top() inside peek_max(): Read-only queries can also hit a stale element left behind by the other structure and must prune before reading index -1 or 0.
  • Using list.remove or del stack[idx] inside popMax: Shifts up to n elements in memory, degrading popMax back to O(n).
  • Assuming the two-stack running-max trick is optimal here: Two stacks give O(1) peekMax, but popMax still takes O(n) time whenever the maximum lies near the bottom.

Alternative approaches

  • Doubly linked list + balanced binary search tree (O(log n) worst-case, O(live) space): Store stack items as nodes in a doubly linked list (a chain of nodes with prev and next pointers supporting O(1) removal of any node given its pointer) and index (value, push_id) -> node inside a balanced binary search tree (a sorted tree like Java's TreeMap or C++'s std::map that finds and removes the maximum key in worst-case O(log n) time). Every deletion unlinks the exact node eagerly with zero stale entries, though Python's standard library lacks a built-in balanced tree, making heap + lazy deletion the cleanest standard-library solution in Python.
  • Two stacks (values + prefix maximums): O(1) for push, pop, top, and peekMax, and O(n) for popMax. Preferable only if popMax is called very rarely compared to push/pop.

Follow-up questions

  • How could you achieve strict worst-case O(log n) time per operation instead of amortized bounds? Lazy deletion is only amortized because one top() call might sweep away thousands of consecutive stale entries at once. Replacing the array stack and heap with a doubly linked list plus a balanced binary search tree keyed by (value, push_id) lets pop() unlink the tail node and erase its tree key in O(log n) worst-case time, and lets popMax() erase the largest tree key and unlink its list node in O(log n) worst-case time (O(1) for top()).
  • If a long-running service performs millions of pushes and pops while keeping only a handful of active items, how would you prevent dead entries from consuming O(total pushes) memory? First, whenever _prune_stack_top or _prune_heap_top discards a stale push_id, call self.removed_ids.remove(push_id) because that item has now exited both structures. Second, track live_count; whenever len(self.stack) > 2 * max(1, live_count) (or similarly for self.max_heap), filter out entries in removed_ids in O(size) time (and call heapq.heapify for the heap), which keeps memory proportional to active items while preserving the exact same amortized time bounds.
  • How would you extend the data structure to also support peekMin() and popMin() with the same tie-breaking rule? Add a third structure self.min_heap storing (value, -push_id) tuples (positive value puts the minimum at the root, while negative -push_id still breaks ties toward the copy closest to the stack top) and a _prune_min_heap_top() helper. Because removed_ids tracks unique push_ids, any removal from stack, max_heap, or min_heap simply adds push_id to removed_ids (only discarding push_id from removed_ids once both remaining structures have pruned it).

Follow-up questions

Similar questions

More Zipline interview questions

All 4 Zipline questions →