Implement a Least-Recently-Used Cache
AnthropicSoftware Engineer · OnsiteLast updated
This question evaluates a candidate's ability to design and implement an efficient in-memory cache with eviction behavior, testing understanding of data structure selection, state management, and time/space complexity under capacity constraints.
Design and implement an in-memory least-recently-used cache.
Requirements:
- The cache is initialized with a positive integer capacity.
- Implement
get(key): return the value associated withkeyif it exists; otherwise return-1ornull. - Implement
put(key, value): insert or update the value forkey. - Any successful
getorputmakes that key the most recently used item. - If inserting a new key causes the cache to exceed capacity, evict the least recently used key.
- Both
getandputshould run in O(1) average time.
Explain your data structures, edge cases, and time/space complexity.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.