Miscellaneous problems · Exercise 83 of 100

Track a least recently used cache

A least recently used cache keeps a fixed number of entries and tracks when each key was last used. Keep the keys in order from oldest use to newest, moving a key to the newest end after a successful read or a write. When a new key needs space in a full cache, remove the key at the oldest end.

Try it yourself

An empty cache holds two keys. Write red, write blue, read red, then write green. Which key does the cache remove?

One-step hint

Line up the keys from oldest to most recently used. Move the read key to the recent end before making room for green.

Worked solution
  1. After the two writes, red is older than blue. Reading red makes red the most recently used key.
  2. The cache is full when green arrives. Blue now has the oldest use, so the cache removes blue.
DSA compiler