Quant Memo
Coding/●●●●●

Design a max-stack

Design a stack supporting push, pop, top, and get_max, report the maximum element currently in the stack, with every operation in O(1)O(1). (Think of tracking the session high of a price series that can also "un-happen" when late corrections retract the most recent ticks.)

s = MaxStack()
s.push(3); s.push(5); s.push(2)
s.get_max() -> 5
s.pop()                 # removes 2
s.get_max() -> 5
s.pop()                 # removes 5
s.get_max() -> 3

The trap: after popping the current maximum, the previous maximum must be recoverable instantly, and a single max_so_far variable cannot rewind.

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions