With use counts in hand, eviction becomes clear, and when the cache is full it throws away the key with the smallest count. Today you make the LFU cache enforce its capacity by dropping the least-used entry.
When at capacity, evict the entry with the lowest frequency before inserting a new key.
Frequency counts exist to answer one question: when the cache is full and a new key
arrives, who has earned the least right to stay? In an LFU cache that is the key
with the smallest use count. So Put, before inserting a brand-new key into a full
cache, scans for the minimum frequency and deletes that entry - the naive O(n) way
for now, made O(1) later in the chapter.
Keep the update path honest: a Put onto an existing key still just overwrites and
counts a use, never evicting, because it does not grow the cache. And a freshly
inserted key starts at frequency 1, which means it is immediately the most
vulnerable entry - a brand-new key can be evicted on the very next insert if
everything else has been used more. That “cold start” is a real weakness of pure
LFU, and it is why the tie-breaking rule in the next lesson matters: when several
keys share the lowest count, you need a principled way to choose between them.
// scan for the lowest-frequency key and drop itfunc (c *LFU) evict() {victim, min := 0, int(^uint(0)>>1) // max intfor k, e := range c.data {if e.freq < min { min, victim = e.freq, k }}delete(c.data, victim)}// in Put, before inserting a brand-new key:// if len(c.data) >= c.cap { c.evict() }