Problem 460471 · medium · Level 04 Non-Linear Data Structures

Thumbnail Cache With Least-Recent Eviction

design · hash map · ordered dict · classes

Design a class ThumbCache that keeps at most capacity rendered thumbnails and throws away the one that has gone unused the longest:

  • ThumbCache(capacity): capacity >= 1.
  • get(key) returns the stored value, or -1 if key is absent. A successful get counts as a use.
  • put(key, value) stores or replaces the value and counts as a use. If the cache then holds more than capacity keys, the least recently used key is removed.

Examples

ops:  ["ThumbCache", "put", "put", "get", "put", "get", "put", "put", "get", "get"]
args: [[2], [7, "x"], [4, "y"], [7], [9, "z"], [4], [7, "X"], [1, "w"], [9], [7]]
Output: [None, None, None, "x", None, -1, None, None, -1, "X"]
Explanation: put(9) evicts key 4, because get(7) made key 7 the more recent. Overwriting key 7
with put(7, "X") refreshes it again, so put(1) evicts key 9.

Constraints

  • 1 <= capacity <= 10**4; keys are integers, values are strings or integers
  • Up to 10**4 calls in total
  • Target: get and put in O(1) average time

Goals

  • Combine a hash map with an order structure for O(1) recency updates
  • Evict the least recently used entry when a fixed capacity is exceeded
Starting Python…