Skip to content
BytePatterns

Cache Hit Ratio for a News Feed

EasySystem Design Cases#lru-cache#hit-ratio~15m

Problem

A news feed service keeps recently viewed posts in an LRU cache in front of its database. Given the sequence of post ids that readers request and the cache capacity in posts, replay the requests: a request for a cached post is a hit and makes it the most recently used; a miss loads the post into the cache, evicting the least recently used post if the cache is over capacity. Return the hit ratio as a percentage rounded to 1 decimal. Call it for several capacities to see how much each extra slot buys. There are up to 1,000,000 requests.

Examples

Input:  feed = ["p1", "p2", "p1", "p3", "p1", "p2", "p4", "p1", "p5", "p2", "p1", "p3"],
        capacities 1, 2, 3 and 4
Output: [0.0, 16.7, 41.7, 50.0]
Why:    the third slot adds the most, because it is enough to keep both hot posts, p1 and p2
Input:  feed = ["a", "b", "c", "a", "b", "c"], capacity = 2
Output: 0.0
Why:    a loop one post longer than the cache evicts each post just before it is needed again
Input:  feed = ["x", "x", "x"], capacity = 1
Output: 66.7
Why:    edge case, only the very first request for a post can miss

Hints

0 / 3

Stuck on the idea rather than the code? Design a Distributed Cache covers it.