Implement an LRU cache
Problem Description
Design and implement an LRU (Least Recently Used) cache that supports the following operations with an average time complexity of O(1):
get(key) -> value: Retrieves the value associated with the givenkey. If thekeyis not found in the cache, return-1. Accessing a key (viagetorput) marks it as the most recently used.put(key, value): Inserts or updates thevaluefor the givenkey. If inserting a new key causes the cache to exceed itscapacity, the least recently used key must be evicted to make space. Updating an existing key also counts as a recent use.
Input/Output Specification
You are required to implement a class or module with:
- A constructor:
LRUCache(capacity) - Two public methods:
get(key)andput(key, value)
Constraints
1 <= capacity <= 10^5- Keys and values are integers (or comparable scalar types).
- The implementation must achieve O(1) average time complexity for both
getandputoperations. - The space complexity must be O(capacity).
AI interview prep
Core dilemma
The central engineering conflict is efficiently maintaining O(1) access/update time for arbitrary keys while simultaneously preserving and updating a strict usage order for O(1) eviction of the least recently used item. This requires harmonizing two distinct data structures to work in concert.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Implement an LRU cache
Problem Description
Design and implement an LRU (Least Recently Used) cache that supports the following operations with an average time complexity of O(1):
get(key) -> value: Retrieves the value associated with the givenkey. If thekeyis not found in the cache, return-1. Accessing a key (viagetorput) marks it as the most recently used.put(key, value): Inserts or updates thevaluefor the givenkey. If inserting a new key causes the cache to exceed itscapacity, the least recently used key must be evicted to make space. Updating an existing key also counts as a recent use.
Input/Output Specification
You are required to implement a class or module with:
- A constructor:
LRUCache(capacity) - Two public methods:
get(key)andput(key, value)
Constraints
1 <= capacity <= 10^5- Keys and values are integers (or comparable scalar types).
- The implementation must achieve O(1) average time complexity for both
getandputoperations. - The space complexity must be O(capacity).