Practice/Amazon/Leetcode 460. LFU Cache
CodingMust
Design and implement a data structure for a cache that evicts entries based on access frequency. The cache should support two operations:
When a key is accessed (via get or put), its frequency counter increments. The cache must efficiently track both frequency and recency to determine which item to evict.
FrequencyCache class with a constructor that takes the cache capacityget method returns the value for the given key, or -1 if not foundput method inserts or updates a key-value pairExample 1:
cache = FrequencyCache(2) cache.put(1, 10) // cache: \{1:10\} cache.put(2, 20) // cache: \{1:10, 2:20\} cache.get(1) // returns 10, cache: \{1:10, 2:20\}, freq(1)=2, freq(2)=1 cache.put(3, 30) // evicts key 2 (lowest frequency), cache: \{1:10, 3:30\} cache.get(2) // returns -1 (not found) cache.get(3) // returns 30 cache.get(1) // returns 10
Example 2:
cache = FrequencyCache(2) cache.put(1, 100) // cache: \{1:100\}, freq(1)=1 cache.put(2, 200) // cache: \{1:100, 2:200\}, freq(1)=1, freq(2)=1 cache.put(3, 300) // both have freq=1, evict key 1 (LRU), cache: \{2:200, 3:300\} cache.get(1) // returns -1