Simulate a Stack with Instant Maximum Access
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests data structure design skills by building a stack that supports O(log n) max retrieval and removal, including removal from the middle when duplicates exist.
Stack with Maximum Operations
Build a data structure that behaves like a stack but also exposes the largest element at any time. You will process a sequence of named operations and return one result per operation.
Operations
| Name | Description | Returns |
|---|---|---|
push(x) | Place integer x on top of the stack | None |
pop | Remove the top element and return it | the removed value |
top | Return the top element without removing it | the top value |
peekMax | Return the largest value currently in the stack without removing it | the max value |
popMax | Remove and return the largest value in the stack. When the largest value appears more than once, remove the copy that is closest to the top. | the removed value |
pop, top, peekMax, and popMax are never called on an empty stack.
Input format
Your function receives two lists of the same length:
ops: a list of operation name strings (e.g."push","pop","peekMax", …)args: a list of argument lists. Forpushthe inner list holds the single integer argument; for every other operation the inner list is empty.
Return a list of results in the same order. Entries corresponding to push are None; all other entries are integers.
Constraints
- 1 ≤ total number of operations ≤ 10 000
- −10 000 ≤ x ≤ 10 000 for every
push - Non-
pushoperations are only called when at least one element is in the stack - Duplicate values are allowed;
popMaxalways removes the topmost among all copies of the maximum
Examples
Example 1
Input: stack_with_max_ops(['push', 'push', 'push', 'top', 'peekMax', 'popMax', 'top', 'pop', 'peekMax'], [[5], [1], [5], [], [], [], [], [], []])
Output: [None, None, None, 5, 5, 5, 1, 1, 5]
Example 2
Input: stack_with_max_ops(['push', 'push', 'push', 'popMax', 'top', 'popMax', 'pop'], [[-2], [0], [-2], [], [], [], []])
Output: [None, None, None, 0, -2, -2, -2]
Hints
Hint 1
A secondary max-stack that mirrors the running maximum handles peekMax cheaply, but think carefully about what happens when the max lives somewhere in the middle and popMax needs to reach it.
Hint 2
If you give every pushed element a unique sequence number, you can break ties in the heap so that equal values always rank the most-recently-pushed one first — which is exactly the element closest to the top.
Hint 3
Removing an arbitrary element from a heap is awkward. Consider marking elements as inactive and skipping over stale heap entries the next time you read the root, rather than removing them immediately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why basic techniques fall short
The simplest augmentation is a secondary "running-max" stack that shadows every push and pop. It keeps peekMax at O(1) and pop at O(1), but popMax still requires popping elements into a temporary buffer until you uncover the maximum, then pushing them all back. That is O(n) per call in the worst case, for example when the maximum was the very first element pushed.
Scanning a plain list for the maximum at query time costs O(n) for both peekMax and popMax.
The efficient design: doubly linked list + max-heap with lazy deletion
Two structures share the same node objects:
Doubly linked list — represents the stack in push order. A pointer called top always refers to the most recently pushed live node. Because every node has prev and next pointers, you can splice any node out of the list in O(1), regardless of whether it sits at the top, the bottom, or the middle.
Max-heap — each entry is the tuple (-value, -index, node).
- Negating
valueconverts Python's min-heap into a max-heap. indexis a monotonically increasing counter assigned at push time. Negating it means that when two entries share the same value, the one with the larger push index wins — that is exactly the copy closest to the top of the stack.- Because indices are unique, the comparison never reaches the
nodefield, so nodes do not need to be orderable or comparable.
Lazy deletion handles the fact that removing an arbitrary entry from a heap mid-structure is expensive. Instead:
- Every node carries an
activeflag, initiallyTrue. popandpopMaxcallremove_node, which unlinks the node from the list and setsactive = False. The node's heap entry is left in place but is now stale.- Before
peekMaxorpopMaxreads the heap root, a helper discards any stale entries by popping them off until the root belongs to a live node.
Operation-by-operation walkthrough
- push(x): Allocate a node, link it after the current
top, updatetop, push the negated-value/negated-index tuple onto the heap. AppendNoneto results. - pop: The node to remove is
top. Record its value, callremove_node(which unlinks it, marks it inactive, and movestopto the predecessor), append the value. - top: Return
top.valuedirectly. - peekMax: Discard stale heap entries, then return the root node's value without popping.
- popMax: Discard stale entries, pop the heap root, record the value, call
remove_nodeon that node.
Why the tie-break rule is correct
Among all copies of the maximum value, the one with the largest push index was pushed most recently and therefore sits closest to the top. The -index key encodes this directly, so heappop always yields the right copy with no extra scanning.
Complexity
Let n be the total number of push operations.
| Operation | Time complexity |
|---|---|
push | O(log n) |
pop | O(1) |
top | O(1) |
peekMax | O(log n) amortized |
popMax | O(log n) amortized |
The amortized bound for peekMax and popMax comes from the fact that each node enters the heap exactly once and leaves it at most once. Across all operations, discard_stale performs at most n heap pops in total — O(n log n) overall — even though a single call can be expensive after a long run of plain pops.
Space: O(n) — stale entries accumulate in the heap until they surface at the root. The heap is bounded by total pushes, not current stack depth. If memory is a concern you could rebuild the heap when the stale count exceeds the live count, preserving the amortized bounds while keeping space proportional to live elements.
Edge cases
- Duplicate maxima:
-indextie-breaking removes the topmost copy. After pushing 5, 1, 5, apopMaxremoves the second 5 and leaves 5, 1. - Max at the top:
remove_nodedetectstop is nodeand movestopback to the predecessor. - Max at the bottom: The node has
prev = None, so only the successor'sprevpointer is updated. - Max removed by a plain
popbeforepopMaxis called: Its heap entry is stale and gets discarded the next timediscard_staleruns. - Negative values: Negating for the heap still works correctly.
Reference solution
import heapq
from typing import List, Optional
class _Node:
__slots__ = ("value", "index", "prev", "next", "active")
def __init__(self, value: int, index: int) -> None:
self.value = value
self.index = index
self.prev: Optional["_Node"] = None
self.next: Optional["_Node"] = None
self.active = True
def stack_with_max_ops(ops: List[str], args: List[List[int]]) -> List[Optional[int]]:
top: Optional[_Node] = None # most-recently-pushed live node
heap: list = [] # entries: (-value, -index, node)
next_index = 0 # monotonically increasing push counter
results: List[Optional[int]] = []
def remove_node(node: _Node) -> None:
nonlocal top
if node.prev is not None:
node.prev.next = node.next
if node.next is not None:
node.next.prev = node.prev
if top is node:
top = node.prev
node.active = False # heap entries for this node are now stale
def discard_stale() -> None:
# pop inactive entries off the heap root until a live one is on top
while heap and not heap[0][2].active:
heapq.heappop(heap)
for op, arg in zip(ops, args):
if op == "push":
node = _Node(arg[0], next_index)
next_index += 1
node.prev = top
if top is not None:
top.next = node
top = node
# Negate value → max-heap from Python's min-heap.
# Negate index → among equal values, highest index (closest to top) wins.
heapq.heappush(heap, (-node.value, -node.index, node))
results.append(None)
elif op == "pop":
node = top # type: ignore[assignment]
results.append(node.value)
remove_node(node)
elif op == "top":
results.append(top.value) # type: ignore[union-attr]
elif op == "peekMax":
discard_stale()
results.append(heap[0][2].value)
elif op == "popMax":
discard_stale()
node = heapq.heappop(heap)[2]
results.append(node.value)
remove_node(node)
return results