I knew the answer involved a hashmap plus a doubly linked list but explaining WHY took me longer than it should have.
Start by clarifying requirements (capacity, eviction policy, thread-safety) and then describe the standard hash map + doubly linked list solution. Explain how each operation achieves O(1) average time and then implement the code, handling edge cases like updating existing keys and evicting the least recently used item.
Pro tip: Mention that you would use a doubly linked list with sentinel head and tail nodes to simplify edge cases, and discuss how to make the cache thread-safe (e.g., with a mutex or concurrent data structures) if needed.
Ask about capacity, eviction policy (LRU), and whether thread-safety is required. Confirm that get and put must be O(1) average time.
Use a hash map for O(1) key lookup and a doubly linked list to maintain recency order. The map stores key -> node, and the list stores nodes with key-value pairs.
For get: if key exists, move node to front (most recently used) and return value; else return -1. For put: if key exists, update value and move to front; else insert new node at front and evict least recently used (tail) if capacity exceeded.
Use sentinel head and tail nodes to avoid null checks. Handle capacity 0 or 1, updating existing keys, and eviction correctly.
Explain that both operations are O(1) average due to hash map and linked list. Mention potential thread-safety using locks or concurrent structures, and trade-offs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.