Now the capacity earns its keep. When the cache is full and a new key arrives, something has to go - and in a FIFO cache the victim is the oldest key. Today you make Put evict, and pin the extreme case of a capacity-1 cache.
When at capacity, evict the oldest key before inserting a new one.
This is the moment a bounded cache becomes real: at capacity, inserting a new key
means evicting an old one. In FIFO order the victim is order[0] - the key that
has waited longest - so Put drops it from both the order slice and the map before
appending the newcomer. An update to an existing key still takes the early
return: it changes a value without inserting, so it never triggers eviction.
Pin the capacity-1 case too, because it is the boundary where the logic is
tightest: a cache that holds a single entry must evict on every single new key, so
the cache only ever remembers the most recent insert. If your eviction is off by
one - evicting after inserting, or comparing > instead of >= - capacity 1 is
where it breaks first. Get that edge right and the general case follows.
// before inserting a brand-new key into a full cache, drop the oldestfunc (c *LRU) Put(key, val int) {if _, ok := c.data[key]; ok { c.data[key] = val; return } // update in placeif len(c.data) >= c.cap {victim := c.order[0] // oldest is first in linec.order = c.order[1:]delete(c.data, victim)}c.order = append(c.order, key)c.data[key] = val}