LRU Cache Implementation
Expert
50 XP
You're trying this as a guest: your result shows here but isn't saved.
Sign in
Implement an LRU (Least Recently Used) cache with O(1) time complexity for both get and put operations.
An LRU cache evicts the least recently used item when the cache reaches its capacity. This data structure is used in operating systems, databases, and web browsers.
Requirements:
LRUCache(capacity) — initialize with a positive capacity.
get(key) — return the value if it exists, otherwise return -1. This counts as a 'use'.
put(key, value) — insert or update the key-value pair. If the cache exceeds capacity, evict the least recently used item.
You may use collections.OrderedDict or implement a doubly-linked list.
To pass
- Get existing key returns its value
- Get evicted key returns -1
- Recently accessed key survives eviction
- Newly added key is accessible
Need a hint?
- collections.OrderedDict remembers insertion order and has move_to_end().
- On get(), move the key to the end (most recently used). On put(), also move to end.
- When over capacity, use popitem(last=False) to remove the first (least recently used) item.