Skip to main content

Implement a thread-safe or TTL LRU cache

Implement get(key) and put(key, val) in O(1) average time with max capacity and optional TTL expiration.

Official Reference

Model Answer & Explanation

from collections import OrderedDict
import time

class TTLLRUCache:
    def __init__(self, cap: int, ttl: float):
        self.cap, self.ttl = cap, ttl
        self.store = OrderedDict()

    def get(self, key):
        if key not in self.store:
            return None
        val, exp = self.store[key]
        if time.monotonic() > exp:
            del self.store[key]
            return None
        self.store.move_to_end(key)
        return val

    def put(self, key, val):
        self.store[key] = (val, time.monotonic() + self.ttl)
        self.store.move_to_end(key)
        if len(self.store) > self.cap:
            self.store.popitem(last=False)

Python’s OrderedDict provides move_to_end(key) and popitem(last=False) in O(1), making LRU concise and clean. Store (value, expires_at) tuples to support TTL expiration lazily on get() and proactively on eviction. Wrap operations in threading.Lock if shared across threads.

Follow-up Interview Question · When is functools.lru_cache dangerous on instance methods or async functions?

Module Context & References

Python & FastAPI · Practice questions & drills High-frequency coding, FastAPI, concurrency and testing exercises
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.