A chat app caches sticker images. Design a class StickerCache that holds at most capacity stickers and,
when it must make room, evicts the one used the fewest times:
StickerCache(capacity):capacity >= 1.get(key)returns the stored value, or-1ifkeyis absent. A successfulgetis one use ofkey.put(key, value)stores or replaces the value. Replacing an existing key counts as one use. A new key starts with a use count of1; if the cache is already full, first evict the key with the smallest use count, and among keys tied on that count, the one whose last use is the oldest.
Examples
ops: ["StickerCache", "put", "put", "put", "get", "get", "put", "get", "get", "put", "get", "get", "get"]
args: [[3], [10, "p"], [20, "q"], [30, "r"], [30], [10], [40, "s"], [20], [40], [50, "t"], [30], [10], [50]]
Output: [None, None, None, None, "r", "p", None, -1, "s", None, -1, "p", "t"]
Explanation: before put(40) key 20 is the only key still at one use, so it is evicted. Before
put(50) keys 10, 30 and 40 are all at two uses; key 30's last use (get(30)) is the oldest, so key 30
is evicted although key 10 was stored before it.
Constraints
1 <= capacity <= 10**4; keys are integers, values strings or integers- Up to
2 * 10**4calls in total - Target:
getandputinO(1)average time; scanning all keys to find the victim is too slow
Goals
- Group keys into buckets by use count so the least used key is found in O(1)
- Break ties inside a bucket by recency
- Track the smallest non-empty use count without scanning