Build a Stack That Also Tracks and Removes the Maximum
Data Structure DesignModel answerLast updated
Design a stack supporting push, pop, top, peekMax, and popMax, with two implementations trading off simplicity against O(log n) worst-case popMax.
Max-Tracking Stack
Design a data structure that behaves like a standard stack but also knows about its maximum element at all times. It must support five operations:
push(x)— add integerxto the top.pop()— remove and return the top element.top()— return the top element without removing it.peekMax()— return the current maximum without removing it.popMax()— remove and return the current maximum. If the same maximum value appears more than once, remove the most recently pushed copy.
All four read/remove operations on an empty structure should raise an error (not silently return a sentinel).
What to implement
Version A — simple auxiliary structure. Use a secondary stack to track the running maximum. Aim for O(1) on push, pop, top, and peekMax. Explain honestly what the complexity of popMax is and why a true amortized O(1) popMax is impossible.
Version B — O(log n) popMax. Use a max-heap combined with a doubly linked list and lazy deletion so that popMax runs in O(log n) amortized time. Describe how you handle the tie-breaking rule for duplicates and how stale heap entries are cleaned up.
For both versions, walk through:
- How duplicates are handled correctly.
- Edge cases: empty structure, all-equal elements, the maximum sitting at the bottom of the stack.
- Time and space complexity of each operation.
- A brief note on what concurrency concerns would look like in a high-throughput setting.
Include working Python code for both versions and at least a handful of test cases that cover the interesting cases.
Hints
Hint 1
For Version A, think about what extra information you can store in parallel with each element so that peekMax is always O(1) — and notice that rebuilding that information after popMax is straightforward if you push elements back through the normal push path.
Hint 2
For Version B, a heap alone isn't enough because you can't remove an arbitrary element from the middle of a heap efficiently. A doubly linked list lets you unlink any node in O(1); combine that with lazy deletion on the heap and you get O(log n) popMax without touching every entry.
Hint 3
Tie-breaking among equal maximums is the subtle part: assign each push a monotonically increasing ID and include it in the heap key so the heap naturally surfaces the most recent copy first.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and key observations
Clarify the contract before writing any code
Three things worth settling up front:
popMaxremoves the most recently pushed copy of the maximum, not just any copy. This matters for implementation and testing.- All read/remove operations on an empty structure should raise
IndexError. Using a sentinel like-1is dangerous because-1can be a valid value. - The prompt mentions "amortized O(1)" for all operations including
popMax. That is impossible for comparison-based data. If you could pushnitems and then callpopMaxntimes each in amortized O(1), you'd sort in O(n) total — which violates the Ω(n log n) lower bound for comparison sorting. Version A therefore gives O(n) worst-case forpopMax. Saying this explicitly is a strong signal; quietly accepting the impossible bound is a red flag.
Version A: two stacks
Keep a main stack s and a parallel max-stack m. m[i] always holds the maximum of s[0..i].
push(x): append tos; appendmax(x, m[-1])tom.pop(): pop from both.peekMax(): returnm[-1].popMax(): pop elements into a temporary buffer until the top ofsequals the current max, remove that element, then push everything in the buffer back throughpush(which correctly rebuildsm).
The first element encountered that equals the max is the most recently pushed copy — that handles duplicates automatically.
| Operation | Time |
|---|---|
| push, pop, top, peekMax | O(1) |
| popMax | O(n) worst case |
Space: O(n).
Version B: heap + doubly linked list with lazy deletion
Structure. Elements live in a doubly linked list in push order — the tail is the stack top. Each node can be unlinked in O(1). A max-heap stores (-val, -id, node) tuples, where id is a monotonically increasing counter assigned at push time.
Why include id in the heap key? Among equal values, the larger id was pushed more recently. Negating it means heapq (a min-heap) naturally pops the most recent copy first — the tie-breaking rule comes for free.
Lazy deletion. pop() unlinks the tail node and marks it alive = False without touching the heap. When peekMax or popMax needs the heap top, it first discards any dead entries from the front of the heap. Each heap entry is popped at most once, so the amortized cleanup cost is O(log n) per live operation.
Space compaction. Stale entries accumulate. When the heap size exceeds roughly 2× the number of live nodes, rebuild the heap from live nodes only. The O(n) rebuild is amortized across all the pops that created the stale entries, so it doesn't change the per-operation complexity.
| Operation | Time |
|---|---|
| push | O(log n) |
| pop, top | O(1) |
| peekMax, popMax | O(log n) amortized |
Space: O(n live) after compaction.
A sorted container (balanced BST keyed by (val, id)) is a cleaner alternative that gives worst-case O(log n) everywhere and eager deletion, but it requires a library or more code.
Edge cases
- Empty structure: every operation that reads or removes must check first and raise
IndexError. - All-equal values:
popMaxdegenerates topopin both versions — no special handling needed. - Max at the bottom: Version A does O(n) work moving everything to the buffer. Version B handles it in O(log n) regardless of position.
- Lazy-deletion interleaving bug:
pop()removes a node that still has a live heap entry. A laterpeekMaxmust skip that entry. Forgetting to mark nodes dead is the classic bug here. - Negative numbers and large values: no sentinels used, so neither causes problems.
Concurrency note
In a high-throughput setting, a simple threading.Lock per instance is the baseline. For finer granularity you'd want to split the lock or use a lock-free structure, but that's a much deeper design discussion — the main point to raise is that lazy-deleted nodes accessed from multiple threads need careful memory ordering.
Python implementation
import heapq
from typing import List, Optional
class MaxStackA:
"""Two parallel stacks: O(1) for everything except O(n) popMax."""
def __init__(self) -> None:
self.s: List[int] = []
self.m: List[int] = [] # m[i] = max of s[0..i]
def _require(self, op: str) -> None:
if not self.s:
raise IndexError(f"{op} from empty MaxStackA")
def push(self, x: int) -> None:
self.s.append(x)
self.m.append(x if not self.m else max(x, self.m[-1]))
def pop(self) -> int:
self._require("pop")
self.m.pop()
return self.s.pop()
def top(self) -> int:
self._require("top")
return self.s[-1]
def peekMax(self) -> int:
self._require("peekMax")
return self.m[-1]
def popMax(self) -> int:
mx = self.peekMax()
buf: List[int] = []
while self.s[-1] != mx:
buf.append(self.pop())
self.pop() # remove the most recent copy of max
for x in reversed(buf):
self.push(x) # push rebuilds m entries correctly
return mx
# ---------------------------------------------------------------------------
class _Node:
__slots__ = ("val", "id", "prev", "next", "alive")
def __init__(self, val: Optional[int], id_: int) -> None:
self.val = val
self.id = id_
self.alive = True
self.prev = self.next = self # circular sentinel initialises to itself
class MaxStackB:
"""Doubly linked list + lazy heap: O(log n) push/peekMax/popMax, O(1) pop/top."""
def __init__(self) -> None:
self.head = _Node(None, -1) # sentinel; head.prev is always the top
self.heap: list = []
self.live = 0
self.counter = 0
def _require(self, op: str) -> None:
if self.live == 0:
raise IndexError(f"{op} from empty MaxStackB")
def _unlink(self, node: _Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
node.alive = False
self.live -= 1
# compact if heap has grown to more than 2x live nodes
if len(self.heap) > 2 * self.live + 32:
self.heap = [e for e in self.heap if e[2].alive]
heapq.heapify(self.heap)
def _clean(self) -> None:
"""Discard dead entries from the heap top."""
while self.heap and not self.heap[0][2].alive:
heapq.heappop(self.heap)
def push(self, x: int) -> None:
node = _Node(x, self.counter)
self.counter += 1
tail = self.head.prev
tail.next = node
node.prev = tail
node.next = self.head
self.head.prev = node
self.live += 1
# negate both so heapq (min-heap) acts as max-heap with correct tie-breaking
heapq.heappush(self.heap, (-x, -node.id, node))
def pop(self) -> int:
self._require("pop")
node = self.head.prev
self._unlink(node)
return node.val
def top(self) -> int:
self._require("top")
return self.head.prev.val
def peekMax(self) -> int:
self._require("peekMax")
self._clean()
return self.heap[0][2].val
def popMax(self) -> int:
self._require("popMax")
self._clean()
node = heapq.heappop(self.heap)[2]
self._unlink(node)
return node.val
# ---------------------------------------------------------------------------
# Quick tests
def _smoke(cls):
ms = cls()
# basic push / pop / top
ms.push(3); ms.push(1); ms.push(5)
assert ms.top() == 5
assert ms.peekMax() == 5
assert ms.pop() == 5
assert ms.peekMax() == 3
# popMax removes most recent duplicate
ms.push(3); ms.push(3) # stack bottom→top: [3, 1, 3, 3]
assert ms.popMax() == 3 # removes top-most 3
assert ms.top() == 3 # next most recent 3 is now on top
assert ms.pop() == 3
assert ms.pop() == 1
# max at the bottom
ms2 = cls()
ms2.push(9); ms2.push(2); ms2.push(1)
assert ms2.popMax() == 9
assert ms2.top() == 1 # remaining order preserved
# empty raises
empty = cls()
for op in (empty.pop, empty.top, empty.peekMax, empty.popMax):
try:
op()
assert False, "expected IndexError"
except IndexError:
pass
print(f"{cls.__name__}: all tests passed")
_smoke(MaxStackA)
_smoke(MaxStackB)
Common mistakes
- Accepting "amortized O(1) popMax" without questioning it.
- Forgetting to push buffer elements back through
pushin Version A, which breaks the max-stackm. - In Version B, marking nodes dead but forgetting to call
_cleanbefore reading the heap top, causing stale entries to be returned. - Using a sentinel return value instead of raising on empty, which silently corrupts results when valid data includes that sentinel.