Design a data structure that acts as a size-limited cache, efficiently storing and retrieving data while prioritizing the most recently accessed entries. This problem tests your understanding of data structures and algorithms, crucial for building performant and scalable systems.
Implement a FrequencyCache class that mimics a cache with a fixed maximum capacity. The cache should support two primary operations: retrieve(key) which returns the value associated with the given key, or -1 if the key is not present; and store(key, value) which adds a new key-value pair to the cache. If the cache is full when store is called, the least frequently used item should be evicted to make room for the new entry. When an item is accessed using retrieve, its frequency should be increased. If multiple items have the same frequency, the least recently inserted of these should be evicted.
Imagine the cache as a simple array. When you need to retrieve a value, you'd have to search the entire array. When you need to store a value and the array is full, you'd iterate through the array to find the least frequently used item and replace it. This involves linear scans for both retrieval and insertion, making it inefficient for larger caches.
Work through this problem with AI coaching and get real-time feedback
Practice This Problem