Skip to main content

Explain a least-recently-used cache and implement a small one with get and put. For example, with capacity 2, after put a, put b, get a, put c, the key b is removed because it was used least recently.

Coding rounds · Intermediate 2

Short answer

An LRU cache holds a fixed number of items and removes the one used longest ago when full. Use collections.OrderedDict: on get, move the key to the end; on put, set it, move it to the end, and if the size exceeds capacity call popitem(last=False). Both operations are O(1); memory is O(capacity).

Deeper answer

First clarify the interface. Ask for the capacity, what get returns on a miss, and whether put on an existing key should update the value and count as a use. Ask whether several threads will share the cache.

The design needs two things: a hash map for O(1) lookup, and an order of use for O(1) eviction. OrderedDict gives both. In get, return None on a miss; on a hit call self.data.move_to_end(key) and return the value. In put, set self.data[key] = value, call move_to_end(key), and then if len(self.data) > self.capacity call self.data.popitem(last=False), which removes the oldest entry. If the interviewer does not allow OrderedDict, describe a dict that maps keys to nodes of a doubly linked list, with the most recent node at the tail.

Test the example from the question, updating an existing key, and capacity 1. Say that for caching a pure function the standard library already has functools.lru_cache(maxsize=1024), and that a shared cache needs a lock.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Python for production

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.