DrawCode Algorithm Visualizer • Linked List • Hard

LRU Cache

Tags: Cache, LRU, Hash Map, Linked List, Design

1. One-Liner

LRU evicts the least recently used entry when capacity is exceeded—needs O(1) get and put.


2. The Problem It Solves

Caches in OS, CDNs, databases, and mobile apps bound memory while keeping hot items.


3. The Core Idea

Hash map for key→node; doubly linked list for recency order (front MRU). get/put splice node to front; evict tail.


4. How It Works (Step-by-Step)

StepAction
1Map key→list iterator/node
2get: if miss return -1; else move to MRU, return value
3put: update or insert; if oversize remove LRU
4Python/Java may use OrderedDict/LinkedHashMap

5. Dry Run Example

Capacity 2: put(1), put(2), get(1) (2 LRU), put(3) evicts 2.


6. Key Properties

PropertyDetail
O(1)Hash + list splice
Thread safetyNeeds locks in prod
Approx LRUClock/NFU cheaper

7. Where It Is Used

Domain / SystemUse
RedisEviction policies
CPUPage replacement analog
MobileImage caches

8. Interview Tips

Discuss OrderedDict caveats, C++ list+unordered_map iterator stability, concurrent LRU with locks or sharding.


9. Comparison with Other Algorithms

TechniqueNotes
FIFOIgnores frequency
LFUCounts hits, heavier
RandomCheaper eviction

10. Complexity

----
TimeO(1) get/put average
SpaceO(capacity)

Implementation Example (PYTHON)

from collections import OrderedDict

class LRUCache:
    def __init__(self, cap):
        self.cap = cap
        self.od = OrderedDict()

    def get(self, k):
        if k not in self.od: return -1
        self.od.move_to_end(k)
        return self.od[k]

    def put(self, k, v):
        if k in self.od:
            self.od.move_to_end(k)
        self.od[k] = v
        if len(self.od) > self.cap:
            self.od.popitem(last=False)

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer