Hard: Advanced Interview · Problem 73 of 82

LRU Cache

HardClassesPython

Write a class LRUCache(capacity) that stores at most capacity key-value pairs and, when full, evicts the least recently used one.

  • get(key) returns the value, or None if the key is missing. A successful get counts as a use of the key.
  • put(key, value) stores the value and counts as a use. Putting an existing key updates its value (and does not evict anything). When a new key would exceed the capacity, first remove the least recently used key.

Understand the problem

Simulate a small cache by hand.

Capacity 2. put("a", 1), put("b", 2), get("a"), put("c", 3). Which key was evicted?

After the first three calls, b is the least recently used: a was just read, so it is the newest, and b is the oldest. Adding c exceeds the capacity, so b goes.

Which standard-library structure is a dictionary that remembers insertion order and lets you move a key to the end in O(1)?

  1. collections.deque
  2. collections.OrderedDict
  3. collections.Counter

OrderedDict has move_to_end(key) and popitem(last=False) (remove the oldest). Together they give O(1) "mark as used" and "evict oldest". (A normal dict also keeps order, but has no move_to_end.)

Write the solution

Write the class.

class LRUCache:
    # Write your code here.
    pass
Hint 1: a question to ask yourself

How can the structure itself tell you which key was used longest ago?

Hint 2: the shape of the answer

Keep an OrderedDict where the end is the most recently used. On a hit, move_to_end(key). On put, store, move_to_end(key), then while it is too big popitem(last=False).

Reflect

Solution

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self._data = OrderedDict()

    def get(self, key):
        if key not in self._data:
            return None
        self._data.move_to_end(key)
        return self._data[key]

    def put(self, key, value):
        self._data[key] = value
        self._data.move_to_end(key)
        if len(self._data) > self.capacity:
            self._data.popitem(last=False)

Another way: a plain dict, which also keeps order

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self._data = {}

    def get(self, key):
        if key not in self._data:
            return None
        value = self._data.pop(key)
        self._data[key] = value
        return value

    def put(self, key, value):
        self._data.pop(key, None)
        self._data[key] = value
        if len(self._data) > self.capacity:
            del self._data[next(iter(self._data))]

What this tests: designing a data structure, OrderedDict, thinking about what operations must be O(1), and edge cases (updating an existing key does not evict).

The idea: a cache must find a key fast (a hash table) and know the order of use (a list). The classic design joins a dictionary and a doubly linked list. OrderedDict is exactly that, built in.

What counts as a use: reading a key (get) and writing it (put, also for an existing key). Forgetting one of them is the commonest mistake.

In real code: functools.lru_cache is an LRU cache for function results. Writing your own is the interview exercise; using the library is the production answer.

Cost: get and put are O(1).

What an interviewer might ask next: Add an expiry time to each entry (a TTL). How does it change get? (Check the age; if too old, delete and return None.)