LRU Cache
Medium Design
LRUCache(capacity) is a cache that holds at most capacity pairs, each a whole-number key and the whole-number value stored under it. When it is full and a new key arrives, it makes room by dropping the pair that has gone unused the longest.
get(key) returns the value stored under key, or -1 when the key is not in the cache. Reading a key counts as using it.
put(key, value) stores value under key, in place of the value already there when the key is in the cache, and counts as using the key. When that leaves more than capacity pairs in the cache, the pair whose key was used longest ago is dropped.
A key that was dropped is gone: get answers -1 for it until it is put again.
Example 1
Reading 5 makes it the newest, so 6 has gone unused the longest and is the pair dropped when 8 arrives.
Example 2
Example 3
Constraints
1 ≤ capacity ≤ 10⁵0 ≤ key ≤ 10⁹and0 ≤ value ≤ 10⁹- at most
10⁵calls in all togetandput
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
See the AI roundMore Design
- Min StackAI round · Medium
- Find Median from Data StreamAI round · Hard
- Time Based Key-Value StoreAI round · Medium
- Serialize and Deserialize Binary TreeHard
- Insert Delete GetRandom O(1)Medium