KatInterview

Build a Stack That Also Tracks and Removes the Maximum

Data Structure DesignModel answer
MediumModel answerData Structure Designstackheaplinked-list

Last 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 integer x to 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.