LRU Cache
Problem Description
Design a Least Recently Used (LRU) cache.
Implement LRUCache(capacity) and:
- get(key): Return value if key exists, else -1. Marks key as recently used.
- put(key, value): Insert/update key. If over capacity, evict the least recently used key.
Both operations must run in O(1) average time.
DE Shaw Tier 1 — LC 146.
Optimal: HashMap + Doubly Linked List. Map gives O(1) lookup. DLL gives O(1) move-to-front and evict-from-back.
Talk-track: 'This is essentially the same eviction policy Redis uses for allkeys-lru. The DLL head is MRU, tail is LRU. On get/put, splice the node to the head. On capacity breach, remove from tail.'
Example Test Cases
Example 1
Input: [["LRUCache","put","put","get","put","get","put","get","get","get"],[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]]
Expected: [null,null,null,1,null,-1,null,-1,3,4]
Example 2
Input: [["LRUCache","put","get"],[[1],[1,1],[2]]]
Expected: [null,null,-1]
Run your code to see the results