Everyone has seen the LeetCode LRU cache. This is the version closer to what a real cache (Redis, a CDN, a database buffer pool) actually needs: alongside get and put, it supports explicit removal and live resizing, and every operation must stay O(1).
Implement LRUCache backed by a hash map + doubly linked list:
__init__(self, capacity: int)get(self, key) -> value — return the value and mark the key most-recently-used; return -1 if the key is absent.put(self, key, value) -> None — insert or update, mark most-recently-used, and evict the least-recently-used entry if over capacity.remove(self, key) -> bool — explicitly delete a key (independent of eviction). Return True if it was present, False otherwise.resize(self, capacity: int) -> None — change the capacity. Shrinking evicts least-recently-used entries until the size fits; growing just raises the ceiling (no eviction).Requirements:
get, put, remove, and a single eviction step must be O(1)Example (capacity = 2):
put(1, 1);put(2, 2);get(1)→ 1;put(3, 3)evicts key 2;get(2)→ -1;put(4, 4)evicts key 1;get(1)→ -1;get(3)→ 3;get(4)→ 4
Constraints:
capacity >= 1; keys and values are integersget on a missing key returns -1resize to a smaller capacity evicts the least-recently-used entries firstOfficial solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.