KatInterview

Simulate a Stack with Instant Maximum Access

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designstackheaplinked-list

Last 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

NameDescriptionReturns
push(x)Place integer x on top of the stackNone
popRemove the top element and return itthe removed value
topReturn the top element without removing itthe top value
peekMaxReturn the largest value currently in the stack without removing itthe max value
popMaxRemove 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. For push the 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-push operations are only called when at least one element is in the stack
  • Duplicate values are allowed; popMax always 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.