Problem 594
LRU Cache
Medium · 20 pts · Design, Hash Table, Linked List
Problem
Simulate a least recently used (LRU) cache with capacity C. 'get k' prints the value stored for key k, or -1 if k is not in the cache; a successful get marks k as just used. 'put k v' stores value v for key k (replacing an old value, which also marks k as just used); if this adds a new key to a full cache, the least recently used key is evicted first. Both operations should run in O(1), for example with a hash map plus a doubly linked list.
Input
The first line contains C and Q. Each of the next Q lines contains 'put k v' or 'get k'. There is at least one get.
Output
Print the result of every get operation, one per line.
Constraints
1 <= C <= 3000; 1 <= Q <= 200000; 0 <= k, v <= 10^5
Example input
2 9 put 1 1 put 2 2 get 1 put 3 3 get 2 put 4 4 get 1 get 3 get 4
Example output
1 -1 -1 3 4
Explanation
With C = 2: put 1 1, put 2 2, get 1 prints 1. put 3 3 evicts key 2 (used least recently), so get 2 prints -1. put 4 4 evicts key 1, so get 1 prints -1, while get 3 and get 4 print 3 and 4.