data-structures · advanced · ~45 min
Combine string hashing with the LRU pattern.
Implement an LRU cache mapping strings to ints:
typedef struct slru slru_t;
slru_t *slru_create(int capacity);
int slru_get(slru_t *c, const char *key, int *out); /* 1=found, 0=missing */
void slru_put(slru_t *c, const char *key, int value);
void slru_destroy(slru_t *c);
On overflow, evict the least-recently-used key. Both get and put count as 'use' on hit.
Real LRU caches in the wild use string keys: URL caches, DNS caches, file path lookups. Combining the data structure with string hashing brings together two big topics.
capacity > 0. Keys <= 64 bytes.
See API.
Use strdup for key storage. Free on eviction and destroy.
typedef struct slru slru_t;
slru_t *slru_create(int capacity);
int slru_get(slru_t *c, const char *key, int *out);
void slru_put(slru_t *c, const char *key, int value);
void slru_destroy(slru_t *c);
Forgetting to move-to-front on get; not freeing the strdup'd key on eviction (leak); using == for string compare.
Capacity 1. Repeated put of same key (update, no eviction).
O(n) lookup in the simple list version; O(1) with a proper hash map.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.