Design an LRU cache
Asked at Two Sigma, Citadel
Design a fixed-capacity key-value cache (think: instrument metadata in front of a slow reference-data service) supporting:
get(key), return the value, or -1 if absent;put(key, value), insert or update; if capacity is exceeded, evict the least recently used entry.
Both get and put count as "uses" of the touched key.
c = LRUCache(2)
c.put(1, 1); c.put(2, 2)
c.get(1) -> 1 # 1 is now most recent
c.put(3, 3) # evicts 2 (least recent)
c.get(2) -> -1
Both operations must run in .
Show a hint
A hash map alone gives O(1) lookup but no recency order. A list gives order but O(n) deletion from the middle. What combination fixes both?
Your answer
This one is open-ended. Work it through, then check your reasoning against the full solution.