Daily iOS
CS fundamentals and algorithms

O(1) max stack

You want a stack, like an editor's undo stack, that returns the "current maximum" of the pushed values in O(1). First define the interface as a Swift protocol, then explain the implementation idea.

protocol MaxStack {
    associatedtype Element: Comparable
    mutating func push(_ x: Element)
    mutating func pop() -> Element?
    func peekMax() -> Element?
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Keep a second stack, maxes, holding the maximum so far alongside the value stack: on push, if the new value is at least the top of maxes, push it there too, and on pop, if the two tops match, pop both. Every operation is O(1), space is O(n).

Share a question