As asked
OpenAI's inference stack needs to cache KV (key-value) states and decoded outputs to serve repeated or similar prompts efficiently. As a warm-up, implement a general LRU cache that supports two operations: get(key) returns the value if the key exists, otherwise -1; put(key, value) inserts or updates the key, evicting the least-recently-used key when the cache is at capacity. Both operations must run in O(1) time.
Sample answer outline
The candidate should reach for a doubly-linked list paired with a hash map. They should explain why a doubly-linked list allows O(1) removal (you need the prev pointer) and why the hash map stores node references, not just keys. A strong answer handles edge cases: capacity of 1, overwriting an existing key without duplicating the node, and moving the accessed node to the head correctly.
Reference implementation (python)
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {} # key -> node
# sentinel head and tail
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
...
def put(self, key: int, value: int) -> None:
...Expect these follow-ups
- How would you make this thread-safe for concurrent access?
- What changes if you need to support a TTL on each entry in addition to LRU eviction?