hardDSA

How do you design an LRU cache?

1.2k views
01

Understand the problem

Explain LRU cache.

lrudesign
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

LRU cache
Run Playground
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = OrderedDict()   # ordered by recency

    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)  # mark most recent
        return self.cache[key]

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.cap:
            self.cache.popitem(last=False)  # evict least recent


# --- demo --- (capacity 2)
lru = LRUCache(2)
lru.put(1, 1); lru.put(2, 2)
print(lru.get(1))     # 1
lru.put(3, 3)         # full -> evicts key 2
print(lru.get(2))     # -1
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.