Problem
Design a cache with a fixed capacity. When the cache is full, it removes the least recently used key. The least recently used key is the key that nobody read or wrote for the longest time.
Write the class LRUCache with these operations:
LRUCache(capacity) creates an empty cache that holds at most capacity keys. get(key) returns the value of key, or -1 if the key is not in the cache. put(key, value) adds the key or changes its value.
If put adds a new key to a full cache, the cache first removes the least recently used key. A get or a put on a key makes it the most recently used key. Each operation must run in O(1) average time.
Example 1
- Input:
- ["LRUCache","put","put","get","put","get","get"] [[2],[1,10],[2,20],[1],[3,30],[2],[3]]
- Output:
- [null,null,null,10,null,-1,30]
- Explanation:
- The
get(1)call makes key 1 recent. Thenput(3, 30)removes key 2, because key 2 is the least recently used key.
Example 2
- Input:
- ["LRUCache","put","put","get"] [[1],[5,50],[5,55],[5]]
- Output:
- [null,null,null,55]
- Explanation:
- The second
putchanges the value of key 5. It does not add a new key.
Constraints
- 1 <= capacity <= 3000
- 0 <= key <= 10^4
- 0 <= value <= 10^5
- At most 2 * 10^5 calls to get and put
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- LFU Cache
Coding · Design · Doubly-Linked List · Hash Table
- All O`one Data Structure
Coding · Design · Doubly-Linked List · Hash Table
- Design Authentication Manager
Coding · Design · Doubly-Linked List · Hash Table
- Design Browser History
Coding · Array · Data Stream · Design
Sources · 4 references
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Aced · 1 record
Anthropic
Implement LRU Cache.
Source date: 12 days ago
Source snapshot: Nov 12, 2026
Hello Interview · 26 records
Amazon
Leetcode 146. LRU Cache
Reported Sep 30, 2026 · 17 source reports
JUNIOR, MID_LEVEL, SENIOR
Source snapshot: Nov 12, 2026
View sourceApple
Leetcode 146. LRU Cache
Reported Jan 19, 2026 · 6 source reports
MID_LEVEL, SENIOR, STAFF
Source snapshot: Nov 12, 2026
View sourceBloomberg
Leetcode 146. LRU Cache
Reported Nov 10, 2025 · 1 source report
MID_LEVEL
Source snapshot: Nov 12, 2026
View source