As asked
Implement an LRU (Least Recently Used) cache that holds up to N items. It should support O(1) get and O(1) put operations. Write it in Swift or Kotlin.
Sample answer outline
Candidate combines a doubly linked list for O(1) insert/remove at head/tail and a hash map from key to node for O(1) lookup. get moves the accessed node to the head. put inserts at the head; if capacity exceeded, removes the tail node and its map entry. Must handle thread safety (synchronized or actor wrapper) if used from multiple queues.
Reference implementation (swift)
class LRUCache<Key: Hashable, Value> {
private class Node {
var key: Key
var value: Value
var prev: Node?
var next: Node?
init(_ key: Key, _ value: Value) { self.key = key; self.value = value }
}
private let capacity: Int
private var map = [Key: Node]()
private let head = Node(/* sentinel */ ...)
private let tail = Node(/* sentinel */ ...)
init(capacity: Int) { ... }
func get(_ key: Key) -> Value? { ... }
func put(_ key: Key, _ value: Value) { ... }
}Expect these follow-ups
- How would you make this thread-safe for concurrent reads and exclusive writes?
- NSCache on iOS does LRU eviction automatically; when would you prefer your custom implementation?