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 integerxas the newest active entry and recordNone.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^9for every"push"valuex- Every
"pop","top","peekMax", and"popMax"call happens on a non-empty container.
Step-by-step walkthrough
Understand the five operations and tie-breaker
We need a LIFO integer container supporting five commands:
push(x): insert integerxas the newest item (producingNonein the output list).pop()andtop(): 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!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()inO(1)time, untilpopMax()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
popMaxfast even when the maximum sits at the bottom, we need a second view ordered by value, plus a way to avoidO(n)middle-of-list deletions.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:self.stack: a plain list of(value, push_id)pairs fortop()andpop().self.max_heap: Python'sheapqmin-heap storing(-value, -push_id)tuples forpeekMax()andpopMax().
Why
(-value, -push_id)? Negatingvalueputs the largest value atmax_heap[0]. When two items share the samevalue, Python compares the second tuple element-push_id: a largerpush_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)frommax_heap, we do not searchself.stackto delete it. Instead, we record2in a hash setself.removed_ids(lazy deletion). Stale entries sit harmlessly inside the other structure until they eventually reachstack[-1]ormax_heap[0], where a tinywhileloop pops and discards them on sight. Because eachpush_identers each structure once and is discarded at most once, cleanup stays fast across any sequence of calls.Implement `push` and the two lazy-cleanup helpers
Why track deletions by
push_idin a set instead of counting values likeremoved_count[8] += 1? Suppose we runpush(8), push(3), popMax(), push(8). The first8(id=0) was removed, and a brand-new8(id=2) is now on top of the stack. A value counter would mistakenly treat the new8on top as deleted! Uniquepush_idintegers 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)Implement `pop`, `top`, `peek_max`, and `pop_max`
Every read or removal operation calls the matching
_prune_*helper first, guaranteeing thatstack[-1](fortop/pop) ormax_heap[0](forpeek_max/pop_max) belongs to a live element:pop()prunesstack, pops(value, push_id), addspush_idtoremoved_ids, and returnsvalue.top()prunesstackand returnsstack[-1][0].peek_max()prunesmax_heapand returns-max_heap[0][0].pop_max()prunesmax_heap, pops(neg_value, neg_push_id), adds-neg_push_idtoremoved_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_valueTrace 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)Complete solution
Finally,
maximum_tracking_stackdispatches each(op, args)pair from the input lists toMaxStackand 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 toself.stackisO(1)and pushing ontoself.max_heapbubbles up a binary heap of height at mostlog2(n).topandpop: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 toself.stackonce and popped fromself.stackat most once (either bypop()or by_prune_stack_top()), sokoperations perform at mostkstack pops in total.peekMaxandpopMax:O(log n)amortized — each pushed item entersself.max_heaponce and isheappop-ed at most once (either bypop_max()or by_prune_heap_top()), charging at most oneO(log n)heap removal to eachpush. Acrossktotal operations, the entire run finishes inO(k log k)time.
- Space:
O(n).self.stack,self.max_heap, andself.removed_idseach store at most one entry per pushed item.
Edge cases
- Duplicate maximums (
push 8, push 3, push 8): Storing-push_idas 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). popMaxremoves the current top element (push 2, push 9, popMax, top):9is popped frommax_heapand added toremoved_ids; the very nexttop()orpop()prunes(9, 1)fromstack[-1]and exposes2.- Re-pushing a value right after
popMaxremoved an older copy (push 8, push 3, popMax, push 8, top): The new8gets a freshpush_id(2), soremoved_ids = {0}never accidentally skips the new8. - Negative numbers and interior maximums (Example 2:
-4, 6, -1, 2): AfterpopMax()removes6andpop()removes2, negating-4and-1stores+4and+1in the min-heap, putting+1(-1) atmax_heap[0]ahead of+4(-4). (Python arbitrary-precisionintvalues never overflow on-x, unlike 32-bitINT_MINin C++/Java.) - Emptying the stack completely and pushing again:
next_idkeeps incrementing, so old IDs inremoved_idsnever 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)8instead of the copy closest to the top! - Tracking lazy deletions by value count (
Counter) instead of uniquepush_id: Fails immediately when the same number is pushed again afterpopMaxremoved an earlier copy deeper in the stack. - Forgetting
_prune_stack_top()insidetop()or_prune_heap_top()insidepeek_max(): Read-only queries can also hit a stale element left behind by the other structure and must prune before reading index-1or0. - Using
list.removeordel stack[idx]insidepopMax: Shifts up tonelements in memory, degradingpopMaxback toO(n). - Assuming the two-stack running-max trick is optimal here: Two stacks give
O(1)peekMax, butpopMaxstill takesO(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 withprevandnextpointers supportingO(1)removal of any node given its pointer) and index(value, push_id) -> nodeinside a balanced binary search tree (a sorted tree like Java'sTreeMapor C++'sstd::mapthat finds and removes the maximum key in worst-caseO(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)forpush,pop,top, andpeekMax, andO(n)forpopMax. Preferable only ifpopMaxis called very rarely compared topush/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)letspop()unlink the tail node and erase its tree key inO(log n)worst-case time, and letspopMax()erase the largest tree key and unlink its list node inO(log n)worst-case time (O(1)fortop()). - 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_topor_prune_heap_topdiscards a stalepush_id, callself.removed_ids.remove(push_id)because that item has now exited both structures. Second, tracklive_count; wheneverlen(self.stack) > 2 * max(1, live_count)(or similarly forself.max_heap), filter out entries inremoved_idsinO(size)time (and callheapq.heapifyfor 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_heapstoring(value, -push_id)tuples (positivevalueputs the minimum at the root, while negative-push_idstill breaks ties toward the copy closest to the stack top) and a_prune_min_heap_top()helper. Becauseremoved_idstracks uniquepush_ids, any removal fromstack,max_heap, ormin_heapsimply addspush_idtoremoved_ids(only discardingpush_idfromremoved_idsonce both remaining structures have pruned it).
Follow-up questions
- How could you achieve strict worst-case O(log n) time per operation instead of amortized bounds?
- 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?
- How would you extend the data structure to also support peekMin() and popMin() with the same tie-breaking rule?
Similar questions
- Object-Oriented Checkers Engine and Move Validator
- Fail-Safe Control System for a Railway Grade Crossing
- Embedded Elevation Mapping and Causal Signal Smoothing
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses