Implement a least-recently-used (LRU) cache with a fixed capacity and process a list of operations.
get kprints the value stored for keyk, or-1if it is not in the cache. A successfulgetmakeskthe most recently used key.put k vstores valuevfor keyk(replacing any old value) and makeskthe most recently used key. If the cache then holds more thancapacitykeys, remove the least recently used one.
Both operations should run in O(1) average time.
Constraints
- 1 ≤ capacity ≤ 10^4
- 1 ≤ number of operations ≤ 10^5, at least one of them a get
- Keys and values are integers between 0 and 10^9
Input and output
- Input
- Line 1: capacity and the number of operations q Next q lines: an operation
- Output
- One line per get: the value or -1.
Examples
Input 1
2 7
put 1 10
put 2 20
get 1
put 3 30
get 2
get 3
get 1Output
10
-1
30
10get 1 makes key 1 recent, so put 3 evicts key 2.
Input 2
1 4
put 5 50
put 5 55
get 5
get 6Output
55
-1Updating a key replaces its value; a missing key gives -1.
Show hints
- A JavaScript Map remembers insertion order, and its first key is the oldest.
- To mark a key as recent, delete it and set it again.
Show the explanation
In JavaScript a Map iterates keys in insertion order, so it can serve as both the hash table and the recency list:
- get: if the key exists, read the value,
deletethe key andsetit again (moving it to the end, the "newest" position). - put: delete the key if present,
setit, and ifsize > capacity, removemap.keys().next().value, the oldest key.
All of these are O(1) on average. In languages without an ordered map, the classic design is a hash map plus a doubly linked list: the map finds the node in O(1), and the list moves or removes nodes in O(1). Python's OrderedDict.move_to_end and popitem(last=False) provide the same structure.
LRU caches appear in browser caches, CDN edges, database buffer pools, and memoisation helpers.
Original UniCircle question. Last reviewed 22 Oct 2026.
