BeginnerCoder

Lesson 24 — LRU cache

LRU cache: forget the least recently used

A cache keeps recent results so you do not recompute or re-download them. It has limited room, so when full it must evict something. LRU (least recently used) evicts the item nobody has touched for the longest. An OrderedDict remembers order: move_to_end(k) marks k as just used, and popitem(last=False) removes the oldest.

from collections import OrderedDict
d = OrderedDict(a=1, b=2)
d.move_to_end("a")      # order: b, a
d.popitem(last=False)   # removes b

Why it matters: browsers, CPUs and databases all use LRU caches.

Want it another way?
Task

In get(), mark k as recently used. In put(), evict the oldest item when there are more than cap. Expected: -1 3 1.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Data Structures

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.