Design LRU caches and bitsets
Design LRU caches and bitsets
An LRU (least recently used) cache evicts the entry that has gone longest without access. A map finds entries by key; a doubly linked list records recency with the newest at the front. A bitset uses one bit per member of a bounded integer universe; it is useful when that universe is dense and known.
package main
import ( "container/list" "fmt")
type entry struct { k string v int}type Cache struct { limit int items map[string]*list.Element order list.List}
func NewCache(n int) *Cache { if n < 0 { n = 0 } return &Cache{limit: n, items: make(map[string]*list.Element)}}func (c *Cache) Get(k string) (int, bool) { e := c.items[k] if e == nil { return 0, false } c.order.MoveToFront(e) return e.Value.(entry).v, true}func (c *Cache) Put(k string, v int) { if c.limit == 0 { return } if e := c.items[k]; e != nil { e.Value = entry{k, v} c.order.MoveToFront(e) return } c.items[k] = c.order.PushFront(entry{k, v}) if c.order.Len() > c.limit { e := c.order.Back() delete(c.items, e.Value.(entry).k) c.order.Remove(e) }}func main() { c := NewCache(2) c.Put("a", 1) c.Put("b", 2) fmt.Println(c.Get("a")) c.Put("c", 3) fmt.Println(c.Get("b")) fmt.Println(c.Get("c"))}Get and Put refresh recency. On overflow, remove the tail from both the list and the map. Updating an existing key must not increase the count. With a fixed capacity, memory is O(capacity) entries; operations use a constant number of map/list operations, not a specification-guaranteed constant runtime. Use NewCache; zero capacity disables storage. Do not copy a used Cache or share it concurrently without synchronization. This cache has no expiration or byte limit.
Expected output:
1 true0 false3 truePack membership into a uint64
package main
import ( "fmt" "math/bits")
type Bits uint64
func (b *Bits) Add(i uint) bool { if i >= 64 { return false } *b |= Bits(1) << i return true}func (b Bits) Has(i uint) bool { return i < 64 && b&(Bits(1)<<i) != 0 }func main() { var b Bits fmt.Println(b.Add(0), b.Add(63), b.Add(64)) fmt.Println(b.Has(63), b.Has(1), bits.OnesCount64(uint64(b)))}The mask 1 shifted left by i selects bit i. OR adds membership; AND tests it; AND NOT clears it. Bound indices explicitly. OnesCount64 counts set bits. A uint64 has exactly 64 positions, while larger bounded sets need multiple words; a map may suit sparse or unbounded keys better.
Expected output:
true true falsetrue false 2Try it locally
Use uint64 masks for sets {1,3} and {3,5}. Compute union with | and intersection with &; print each number of set bits using bits.OnesCount64.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 07: Design LRU caches and bitsets
Check the lesson objective before moving on.
Which entry does LRU evict after accessing an older entry?
Which bitwise operator computes intersection?