Python coding

Cache that evicts the least-used key

Write a class LFUCache that stores at most capacity key-value pairs and follows the least-frequently-used (LFU) policy.

  • get(key) returns the value stored for key, or -1 if the key is absent.
  • put(key, value) stores the pair, overwriting any old value. If key is new and the cache is already full, it first evicts the key with the fewest uses; among keys tied on uses, the one that has gone longest without a use goes.

Each key counts its uses while it is stored: a put, and a get that finds the key, each add one, so a new key starts at 1. Both operations must be O(1) on average. Keys and values are non-negative integers and capacity >= 1.

The tests call the provided run_cache(capacity, ops): it builds the cache, applies each operation in order and returns the list of results (None for put, shown as null).

Besides the tests, one large input (3,000 keys, 2,000 evictions) with a ~350 ms limit (scaled to your device's speed): brute force won't pass.

  • run_cache(2, [["put",1,10],["put",2,20],["get",1],["put",3,30],["get",2],["get",3],["get",1]]) → [null,null,10,null,-1,30,10]
  • run_cache(2, [["put",1,1],["put",2,2],["get",1],["get",2],["put",3,3],["get",1],["get",2],["get",3]]) → [null,null,1,2,null,-1,2,3]
  • run_cache(2, [["put",5,50],["put",6,60],["get",5],["get",5],["get",6],["put",7,70],["get",5],["get",6],["get",7]]) → [null,null,50,50,60,null,50,-1,70]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Bucket the keys by use count, and keep each bucket in order of last use: an OrderedDict per count. The victim is then the oldest key of the lowest bucket.

Hint 2

A use moves a key from bucket n to the end of bucket n + 1. Track the lowest non-empty count in one variable instead of searching for it.

Hint 3

That minimum only changes two ways: a new key resets it to 1, and a key leaving the last slot of the minimum bucket raises it by one. Evict before inserting.

Solution and why it works
pythonO(1) average per operation · O(capacity)
# --- your code ---
from collections import defaultdict, OrderedDict


class LFUCache:
    def __init__(self, capacity: int):
        self.capacity, self.least = capacity, 0      # least: fewest uses among stored keys
        self.values, self.uses = {}, {}              # key -> value, key -> times used
        self.by_uses = defaultdict(OrderedDict)      # times used -> its keys, least recent first

    def _unlink(self, key: int) -> None:             # forget key, dropping an emptied bucket
        n = self.uses.pop(key)
        del self.values[key], self.by_uses[n][key]
        if not self.by_uses[n]:
            del self.by_uses[n]

    def get(self, key: int) -> int:
        if key in self.values:
            self.put(key, self.values[key])          # a read is a use, like rewriting the value
        return self.values.get(key, -1)

    def put(self, key: int, value: int) -> None:
        n = self.uses.get(key, 0)                    # 0: a new key
        if n:
            self._unlink(key)
        elif len(self.values) == self.capacity:      # evict first, so the newcomer stays
            self._unlink(next(iter(self.by_uses[self.least])))
        if not n or (self.least == n and n not in self.by_uses):
            self.least = n + 1                       # no stored key has fewer uses now
        self.values[key], self.uses[key] = value, n + 1
        self.by_uses[n + 1][key] = None              # newest at the end of its bucket


# --- provided: do not edit ---
def run_cache(capacity: int, ops: list[list]) -> list:
    cache = LFUCache(capacity)
    return [getattr(cache, name)(*args) for name, *args in ops]

Two maps hold each key's value and use count, and one OrderedDict per count keeps its keys from least to most recent, so the victim is the first key of the lowest bucket. A use moves a key one bucket up. least never needs a search: a new key makes it 1, and a key leaving the minimum bucket empty makes it n + 1, where that key just landed. The traps: inserting before evicting (the newcomer can evict itself) and scanning every key for the victim, O(capacity) per eviction.