Daily iOS
CS fundamentals and algorithmsApple

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?
}

Submit