Python 3D Academyবাংলা

The LFU cache: forget what is used least

🌍 In real life. A tea stall's shelf has room for only two jars. When a new kind of tea arrives and the shelf is full, which jar goes to the storeroom? The LRU rule of Lesson 63.1 removes the jar used longest ago. But the masala tea is asked for fifty times a day and lemon tea twice a week; one quiet hour shouldn't banish the masala. The LFU rule (least frequently used) removes the jar used the fewest times, and among jars used equally often, the one used longest ago.

Keeping that rule exact, with every get and put in O(1), is LeetCode 460, a Hard design question.

The idea in one sentence: count the uses of every key, keep the keys in groups by their count (each group ordered from least to most recently used), and remember the smallest count, so the key to remove is always the first one in the smallest group.

Its words:

  • LFU: least frequently used: evict the key with the fewest uses; break ties by least recent use
  • use count: how many gets and puts a key has had since it entered the cache
  • group: an ordered dict of all keys with the same count, oldest use first
  • least: the smallest count that has a group; it changes only by small steps

The rule first, step by step. Before the fast structure, here is the rule itself, written plainly: count the uses, remember when each key was last used, and on eviction pick the smallest (uses, last use). With room for 2: put 1, put 2, get 1, put 3, get 3, put 4:

Making it O(1). min(...) over every key is O(n) per eviction. Three structures remove the search:

  1. value and uses: dicts from key to value and to use count.
  2. groups[n]: an OrderedDict of the keys used exactly n times, in order of their last use. Moving a key to the end, deleting it, and taking the first one (popitem(last=False)) are all O(1).
  3. least: the smallest n with a group. A get or put of an existing key moves it from group n to n + 1, so least can only grow by 1 (when group n empties and n was least). A new key always has 1 use, so after an insert least is 1.

Why it is correct. The first key of groups[least] has the fewest uses (no smaller group exists) and, within its group, the oldest last use (groups are kept in order of use). That is exactly the key the LFU rule says to remove.

What it costs, by counting. Every operation does a fixed number of dict and ordered-dict steps: O(1) for get and put, O(capacity) memory. Compare the LRU cache: one ordered list of keys. LFU needs one ordered list per use count, plus least.

from collections import OrderedDict, defaultdict


class LFUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.value = {}                     # key -> value
        self.uses = {}                      # key -> how many times it was used
        self.groups = defaultdict(OrderedDict)  # uses -> keys, least recent first
        self.least = 0                      # the smallest use count in the cache

    def _touch(self, key):                  # one more use: move key up a group
        n = self.uses[key]
        del self.groups[n][key]
        if not self.groups[n]:
            del self.groups[n]
            if self.least == n:
                self.least = n + 1
        self.uses[key] = n + 1
        self.groups[n + 1][key] = None      # newest at the end

    def get(self, key):
        if key not in self.value:
            return -1
        self._touch(key)
        return self.value[key]

    def put(self, key, value):
        if self.capacity == 0:
            return
        if key in self.value:
            self.value[key] = value
            self._touch(key)
            return
        if len(self.value) == self.capacity:
            old, _ = self.groups[self.least].popitem(last=False)  # least recent
            if not self.groups[self.least]:
                del self.groups[self.least]
            del self.value[old], self.uses[old]
        self.value[key] = value
        self.uses[key] = 1
        self.groups[1][key] = None
        self.least = 1                      # a new key has been used once


cache = LFUCache(2)
cache.put(1, "masala")
cache.put(2, "lemon")
print(cache.get(1))
cache.put(3, "ginger")                      # 2 has the fewest uses: it goes
print(cache.get(2), cache.get(3))
cache.put(4, "mint")                        # 1 and 3 tie on uses; 1 was used longer ago
print(cache.get(1), cache.get(3), cache.get(4))
The same answers as LeetCode 460's example: 1 and 3 tie at two uses, and the one used longer ago leaves.

Mistakes and edge cases.

  • Removing the newest key on a tie. popitem() with the default last=True takes the most recently used key; LFU wants the least recent: popitem(last=False).
  • Not counting put on an existing key as a use. Updating a value is a use: move the key up a group.
  • Forgetting to reset least to 1 after inserting. A new key has 1 use, so it is now the least used, even if least was 5.
  • Leaving empty groups behind. If an empty group stays, groups[least] may be empty when you evict from it.
  • Capacity 0. Nothing can be stored: put must do nothing (otherwise eviction pops from an empty group).

Quiz

  1. What does this print?

    from collections import OrderedDict, defaultdict
    
    
    class LFUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.value = {}                     # key -> value
            self.uses = {}                      # key -> how many times it was used
            self.groups = defaultdict(OrderedDict)  # uses -> keys, least recent first
            self.least = 0                      # the smallest use count in the cache
    
        def _touch(self, key):                  # one more use: move key up a group
            n = self.uses[key]
            del self.groups[n][key]
            if not self.groups[n]:
                del self.groups[n]
                if self.least == n:
                    self.least = n + 1
            self.uses[key] = n + 1
            self.groups[n + 1][key] = None      # newest at the end
    
        def get(self, key):
            if key not in self.value:
                return -1
            self._touch(key)
            return self.value[key]
    
        def put(self, key, value):
            if self.capacity == 0:
                return
            if key in self.value:
                self.value[key] = value
                self._touch(key)
                return
            if len(self.value) == self.capacity:
                old, _ = self.groups[self.least].popitem(last=False)  # least recent
                if not self.groups[self.least]:
                    del self.groups[self.least]
                del self.value[old], self.uses[old]
            self.value[key] = value
            self.uses[key] = 1
            self.groups[1][key] = None
            self.least = 1                      # a new key has been used once
    
    
    c = LFUCache(2)
    c.put("a", 1)
    c.put("b", 2)
    c.get("a")
    c.get("a")
    c.get("b")
    c.put("c", 3)
    print(c.get("a"), c.get("b"), c.get("c"))
  2. Two keys in an LFU cache have the same use count. Which is evicted?

    • The one whose last use was longer ago
    • The one that was inserted last
    • Both
  3. Why can the smallest use count be kept in one variable instead of being searched for?

    • A use moves a key up by exactly one count, and a new key always starts at 1
    • Counts never change
    • There is only one group
  4. With capacity 2, after put(1), put(2), put(3), get(2) should still find key 2 (key 1 was the least recent), but returns -1. Which line is wrong?

    def put(self, key, value):
        if self.capacity == 0:
            return
        if key in self.value:
            self.value[key] = value
            self._touch(key)
            return
        if len(self.value) == self.capacity:
            old, _ = self.groups[self.least].popitem()
            if not self.groups[self.least]:
                del self.groups[self.least]
            del self.value[old], self.uses[old]
        self.value[key] = value
        self.uses[key] = 1
        self.groups[1][key] = None
        self.least = 1

Coding tasks

  1. Write LFUCache(capacity) with get(key) (the value, or -1) and put(key, value), both O(1). When full, evict the key with the fewest uses (gets and puts), and among those the least recently used.

  2. Write lfu_victims(capacity, ops), the plain version of the rule: ops is a list of ("get", key) and ("put", key); return the keys evicted, in order. A put or a successful get is a use; ties go to the least recently used. (O(n) per eviction is fine here.)