Data Structures
20 min
Redis is an in-memory data structure server — beyond simple key-value storage, it natively supports lists, sets, hashes, and sorted sets, each with efficient built-in operations. One of Redis's most common uses is exactly the LRU cache pattern from the Operating Systems course's Virtual Memory module — same eviction idea, applied to an application-level cache instead of OS memory pages:
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.order = [] # tracks recency, oldest first
def get(self, key):
if key not in self.cache:
return -1
self.order.remove(key)
self.order.append(key) # mark as most-recently-used
return self.cache[key]
Accessing 'a' via get() before the eviction is what saves it -- without that access, 'a' would have been the LRU key and gotten evicted instead of 'b'.
Real Redis operations map directly onto structures you already know:
LPUSH/RPUSH (list push), SADD (set add), HSET (hash/dict set),
ZADD (sorted set — like a dict where values are also sortable
scores). Choosing the RIGHT Redis structure for a job is usually just
recognizing which Python built-in type the problem already maps to —
a leaderboard is a sorted set, a "has this user done X" check is a set,
a user's profile fields are a hash.
Given the `LRUCache` class and a module-level `cache = LRUCache(2)` instance below, implement `put(self, key, value)`: if `key` already exists, refresh its recency; otherwise, if the cache is at capacity, evict the least-recently-used key first, then insert.
`build_scenario()` (given) creates a capacity-2 cache, puts 'a' then 'b', accesses 'a' again, then puts 'c' (forcing an eviction). Write `check_evicted(cache, key)`, returning True if `key` was evicted (`cache.get(key) == -1`).
Redis is often described as a 'data structure server.' What does that mean, compared to a typical key-value store?
You can implement an LRU cache from scratch, and recognize which native Redis data structure maps onto a given application need.