As asked
Implement a Least Recently Used cache class in TypeScript with get(key) and put(key, value) methods, both running in O(1) time. The cache has a fixed capacity and evicts the least recently used entry when full.
Sample answer outline
Use a doubly-linked list for O(1) move-to-front and a Map for O(1) key lookup. The Map stores references to list nodes. On get, move the node to the head. On put, insert at head and evict the tail if over capacity. A strong answer writes clean TypeScript generics and handles the edge case of updating an existing key.
Reference implementation (typescript)
class LRUCache<K, V> {
private capacity: number;
// TODO: add your data structures here
constructor(capacity: number) {
this.capacity = capacity;
}
get(key: K): V | -1 {
// implement
}
put(key: K, value: V): void {
// implement
}
}
Expect these follow-ups
- Why does a Map plus a doubly-linked list give you O(1) rather than O(n) for eviction?
- How would you make this cache thread-safe in a multi-threaded environment?