Question presented to candidate: "Implement an LRU cache in Python with get and put both in O(1), without using OrderedDict. Explain why you need a doubly linked list together with a hash map, and what would go wrong with an array or a singly linked list."
What a strong answer should cover:
- The three required operations: find by key, move any entry to the most-recent end, evict the least-recent end, all in O(1).
- Why each alternative fails: list of keys (O(n) shifts), dict only (no order), heap or tree (O(log n)), singly linked list (O(n) to find the predecessor).
- Doubly linked list with sentinel head and tail; the dict maps key to node; the node stores its key for eviction.
- Exact steps: unlink is 2 pointer writes, push front 4; eviction is
tail.prevplusdel self.map[node.key]. - Python details: a small
Nodeclass with__slots__,dict.getfor the lookup, identity checks withisfor sentinels, andOrderedDictas the library equivalent.
Clarifying questions expected:
- May I use
OrderedDict, or should I build the list myself? - Does
puton an existing key count as a use? - Can capacity be 0?
Code / implementation expected: Yes — an LRUCache class with a Node class, a dict and two sentinels in Python 3.