Skip to main content

Your program is running slowly because it's accessing data from disk over and over again. To improve the performance, you want to build a simple key-value store to cache this data in memory, but you also want to limit the amount of memory used. You decide to build a caching system that only keeps the N most recently used items—also known as a least recently used (LRU) cache.

Write a class LRUCache(n) that accepts a size limit n. It should support a set(key, value) method for inserting or updating items and a get(key) method for retrieving items. Can you implement a solution where both of these methods run in O(1) time?

Python
class LRUCache(n): set(key, value) get(key)

Examples

To make room for new items, the least recently used item should be removed. An item is 'used' whenever it is set, retrieved, or updated.

Python
cache = LRUCache(2) # Limit of 2 items cache.set('user1', 'Alex') cache.set('user2', 'Brian') cache.set('user3', 'Chris')

Here user1 is empty because it was the least recently used and thus removed to make room for user3:

Python
cache.get('user1') # => None cache.get('user2') # => 'Brian' cache.get('user3') # => 'Chris'

If you're having trouble getting started, think about which data structure(s) you can use to solve this problem. Which one is best for a key-value store? Which one can help you store items in order of recency?

You'll need to be able to find and remove the least recent item in O(1) time, so some sort of ordered list is necessary. An array won't work because moving items around takes O(n) time. Could you combine two different data structures to maintain this order and also get fast lookups?

You can use a doubly linked list to store the items in the correct order. When an item is used, just move its node to the front of the list. The least recently used node will always end up at the end of the list.

To look up items without traversing the entire list, you can also add a hash table that maps from the key to the item's node.

Whats the time complexity of your solution?