Implement LRU and LFU caches
VerkadaSoftware Engineer · OnsiteLast updated
This question evaluates understanding of cache eviction policies and data structure design, focusing on LRU and LFU semantics and the ability to support O(1) average-time get/put operations.
Implement two in-memory cache classes with fixed capacity:
- Recent-use cache
get(key): return the value forkey, or-1if the key does not exist.put(key, value): insert or update the key.- When the cache is full, evict the least recently used entry.
- Target time complexity: O(1) average for both operations.
- Frequency-based cache
- Support the same
getandputAPI. - When the cache is full, evict the entry with the lowest access frequency.
- If multiple entries have the same frequency, evict the least recently used among them.
- Target time complexity: O(1) average for both operations.
Be prepared to explain the data structures you choose and how you would test edge cases such as updates, repeated reads, and eviction order.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.