Loading...
Loading...
A store keeps the details of its most recently used products in a cache of capacity C. PUT k v stores the value v for the key k, or replaces it if k is already there. GET k prints the value of k, or -1 if k is not in the cache. Both commands count as a use of k. When a PUT makes the cache hold more than C keys, the least recently used key is removed.
PUT k v or GET k.GET: the value or -1.Example
Input
2 7 PUT 1 10 PUT 2 20 GET 1 PUT 3 30 GET 2 GET 3 GET 1
Output
10 -1 30 10
GET 1 makes 1 recent, so PUT 3 removes key 2.
Try the problem first. Open one hint at a time.
Think of a LinkedHashMap that keeps access order. Its third constructor argument must be true.
Override removeEldestEntry to return size() > C. Read C before you create the map, and keep it final (or effectively final).
GET on a missing key returns null; print -1 in that case.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor