15% off all plans & roadmaps Use code

See plans

LFU Cache

Updated

TL;DR: Design a cache that evicts the least frequently used key and breaks ties by least recent use, with O(1) get and put. Keep a map from each frequency to an ordered bucket of keys, and track the smallest frequency in use.

Problem

Design and implement a data structure for a Least Frequently Used (LFU) cache.

Implement the LFUCache class:

  • LFUCache(int capacity) initializes the object with the capacity of the data structure.
  • int get(int key) returns the value of key if it is in the cache. Otherwise, it returns -1.
  • void put(int key, int value) updates the value of key if it is present. If it is not present, it inserts key. When the cache is full, it removes the least frequently used key before it inserts the new item. If two or more keys tie on frequency, it removes the least recently used key among them.

Each key has a use counter. A new key starts with a counter of 1 when put inserts it. The counter goes up by one each time get or put is called on that key while it is in the cache. The key with the smallest counter is the least frequently used key.

Both get and put must run in O(1) average time.

Example 1

Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output: [null, null, null, 1, null, -1, 3, null, -1, 3, 4]
Explanation: The cache holds 2 keys. Putting key 3 evicts key 2, which has the smallest counter. Putting key 4 evicts key 1, because keys 1 and 3 tie at 2 and key 1 was used less recently.

Constraints

  • 1 <= capacity <= 10^4
  • 0 <= key <= 10^5
  • 0 <= value <= 10^9
  • At most 2 * 10^5 calls will be made to get and put.

Constraints that matter

  • At most 2 * 10^5 calls with a capacity of up to 10^4 means a scan of the cache on every put costs up to 2 * 10^9 steps. Eviction must find the victim without a scan.
  • Counters start at 1 and rise by exactly one per use. A key therefore only ever moves from bucket f to bucket f + 1, which keeps the bookkeeping small.
  • Ties need recency. Two keys with the same counter must be ordered by last use, so each bucket has to keep insertion order.
  • Values go up to 10^9 and keys up to 10^5, so you can store them in hash maps directly. No array indexed by key is needed.

View on LeetCode

Hints

Hint 1

This is a design problem.

Hint 2

Store each key with its value, its use counter, and the time of its last use.

Solution

Intuition

This is a design problem. Every operation must be O(1), but each eviction has to find the least frequent key and, among ties, the least recent one. A single scan cannot meet that bound, so the pattern to reach for is a hash map of frequency buckets, where each bucket keeps its keys in recency order.

Picture a set of numbered bins, one per use count, with people standing in arrival order inside each. The bin number is the frequency, the line order is recency, and eviction removes the person at the front of the lowest nonempty bin.

The key detail is that a counter only moves up by one per use. When a key is touched, it leaves bucket f and joins bucket f + 1. You only need to track one integer, the smallest counter that is currently non-empty. Each touch can update that integer in constant time.

It works because the least frequent key always sits in the bucket at minFreq. Inside that bucket, the first key has the oldest last use, since every touch appends the key to the end. Eviction therefore reads one front element and removes it.

Watch the pattern animation

Worked example

Input: capacity = 1, operations in order: put(1, 100), put(2, 200), get(2), put(3, 300), get(1), put(3, 350), get(3), get(1)
Output: [null, null, null, 200, null, -1, null, 350, -1]
Explanation: With capacity 1, every new key evicts the single key already stored. The get calls on key 2 and key 3 raise their counters, and the put on key 3 updates its value instead of evicting it. The two missing-key lookups return -1.

Approach 1: Brute force

Store each key with its value, its use counter, and the time of its last use. When a put needs room, scan every entry for the smallest pair of (counter, time). Each get and put touches only one entry, but eviction reads all of them.

Steps

  1. Keep a map from key to an entry that holds the value, the counter, and the last-use time.
  2. Keep a clock that goes up by one on every get and every put.
  3. For get, return -1 on a missing key. Otherwise raise its counter and set its time to the clock.
  4. For put on an existing key, set the value, raise the counter, and set the time.
  5. For put on a new key with a full cache, scan all entries for the smallest (counter, time) pair and delete it.
  6. Insert the new key with counter 1 and the current time.

Dry run

Trace on the example, capacity 1, clock starts at 0.

  • put(1, 100): clock 1. Cache is empty, store key 1 with counter 1, time 1.
  • put(2, 200): clock 2. The cache is full, and the scan finds only key 1, so delete it. Store key 2 with counter 1, time 2.
  • get(2): clock 3. Counter becomes 2, time 3. Return 200.
  • put(3, 300): clock 4. The scan finds only key 2, so delete it. Store key 3 with counter 1, time 4.
  • get(1): clock 5. Key 1 is missing. Return -1.
  • put(3, 350): clock 6. Key 3 exists. Value becomes 350, counter 2, time 6.
  • get(3): clock 7. Counter becomes 3. Return 350.
  • get(1): clock 8. Key 1 is missing. Return -1.

The outputs are null, null, 200, null, -1, null, 350, -1, which matches the expected output.

Complexity

TimeO(C) per put on a full cache, O(1) per get
SpaceO(C)

Let C be the capacity. A get does one hash lookup and one field update, so it costs O(1). A put on a full cache scans all C entries before it inserts, so it costs O(C). Across 2 * 10^5 calls with C up to 10^4, the worst case is about 2 * 10^9 steps, which is too many. Space is O(C) because the map holds at most C entries.

PythonTested in our runner

class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.clock = 0
        self.data = {}  # key -> [value, counter, last_used]

    def get(self, key: int) -> int:
        self.clock += 1
        if key not in self.data:
            return -1
        entry = self.data[key]
        entry[1] += 1
        entry[2] = self.clock
        return entry[0]

    def put(self, key: int, value: int) -> None:
        if self.capacity == 0:
            return
        self.clock += 1
        if key in self.data:
            entry = self.data[key]
            entry[0] = value
            entry[1] += 1
            entry[2] = self.clock
            return
        if len(self.data) >= self.capacity:
            # Full scan: smallest counter, then oldest last use
            victim = min(self.data, key=lambda k: (self.data[k][1], self.data[k][2]))
            del self.data[victim]
        self.data[key] = [value, 1, self.clock]

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Frequency buckets with recency orderOptimalDesign (General/Specific)

What's slow in the brute force: eviction reads every entry to find the minimum. The insight that fixes it: a counter only rises by one per use, so a key only moves from bucket f to bucket f + 1. Keep one insertion-ordered bucket per counter and one integer for the smallest non-empty counter. The least frequent key is then in bucket minFreq, and the first key in that bucket is the least recently used.

Steps

  1. Keep vals (key to value), freq (key to counter), buckets (counter to an insertion-ordered set of keys), and minFreq.
  2. To touch a key, remove it from buckets[freq[key]]. If that bucket is now empty, delete it, and if its counter was minFreq, set minFreq to counter + 1.
  3. Raise freq[key] by one and append the key to buckets[new counter], which makes it the most recent in that bucket.
  4. For get, return -1 on a missing key. Otherwise touch the key and return its value.
  5. For put on an existing key, set the new value and touch the key.
  6. For put on a new key with a full cache, take the first key of buckets[minFreq], delete it from every map, and delete the bucket if it is now empty.
  7. Insert the new key with counter 1, append it to buckets[1], and set minFreq to 1.

Dry run

Trace on the example, capacity 1. Each row is one call. The bucket column lists keys from least recent to most recent.

StepCallvalsfreqbucketsminFreqReturns
1put(1, 100){1: 100}{1: 1}{1: [1]}1null
2put(2, 200){2: 200}{2: 1}{1: [2]}1null
3get(2){2: 200}{2: 2}{2: [2]}2200
4put(3, 300){3: 300}{3: 1}{1: [3]}1null
5get(1){3: 300}{3: 1}{1: [3]}1-1
6put(3, 350){3: 350}{3: 2}{2: [3]}2null
7get(3){3: 350}{3: 3}{3: [3]}3350
8get(1){3: 350}{3: 3}{3: [3]}3-1

At step 2, the cache is full, so key 1 is evicted from bucket 1. At step 3, bucket 1 empties and minFreq moves to 2. The returns read down the last column give null, null, 200, null, -1, null, 350, -1, which matches the expected output.

Complexity

TimeO(1)
SpaceO(C)

Let C be the capacity. Each get or put performs a fixed number of hash map reads, writes and deletes. It also performs a fixed number of appends and removals in one bucket, which are O(1) with a linked structure. Eviction reads only the first key of bucket minFreq, so time is O(1). Space is O(C) because the maps and buckets hold at most C keys in total.

PythonTested in our runner

from collections import OrderedDict, defaultdict

class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.min_freq = 0
        self.vals = {}
        self.freq = {}
        self.buckets = defaultdict(OrderedDict)  # counter -> keys, LRU first

    def _touch(self, key: int) -> None:
        f = self.freq[key]
        bucket = self.buckets[f]
        del bucket[key]
        if not bucket:
            del self.buckets[f]
            if self.min_freq == f:
                self.min_freq = f + 1
        self.freq[key] = f + 1
        self.buckets[f + 1][key] = None  # most recent goes last

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

    def put(self, key: int, value: int) -> None:
        if self.capacity == 0:
            return
        if key in self.vals:
            self.vals[key] = value
            self._touch(key)
            return
        if len(self.vals) >= self.capacity:
            bucket = self.buckets[self.min_freq]
            victim, _ = bucket.popitem(last=False)  # least recent in min bucket
            if not bucket:
                del self.buckets[self.min_freq]
            del self.vals[victim]
            del self.freq[victim]
        self.vals[key] = value
        self.freq[key] = 1
        self.buckets[1][key] = None
        self.min_freq = 1

Common mistakes

  • Raising minFreq on every touch, for example minFreq += 1 unconditionally. Only move it when the emptied bucket was the minimum (if minFreq == f). Otherwise the minimum drifts above the real smallest counter.
  • Evicting from the most recent end of buckets[minFreq]. Touches append to the end, so the front holds the least recent key. Pop the front, not the back.
  • Updating the value in put on an existing key without touching it. An update counts as a use, so the counter and recency must change too.
  • Leaving minFreq unchanged after the last key of the minimum bucket is evicted. The new key starts at counter 1, so set minFreq = 1 on every insert.
  • Checking size >= capacity after inserting, or running eviction when capacity == 0. With capacity 0, put must return before it touches any structure.
  • In the brute force, comparing only the counter during eviction. Ties need the last-use time too, so min by counter alone can evict the more recent key.

Edge cases

  • Capacity 1: each new key evicts the only stored key, and the counter of the stored key does not matter.
  • get on a missing key returns -1 and changes no counter, no bucket, and no minFreq.
  • put on an existing key updates the value and counts as a use, so that key is protected from the next eviction.
  • All keys tied on counter 1: eviction removes the least recently inserted key, which is the front of bucket 1.
  • Key 0 and value 0 are valid inputs and must be stored like any other value.
  • Capacity 0: every put is ignored and every get returns -1.

Follow-ups interviewers ask

What if every key has the same counter all the time? Does the design still work?
Yes. Every key sits in one bucket, so the structure reduces to an LRU cache. Touching a key moves it to the end, and eviction still removes the front, so every operation stays O(1).
Can you avoid a hand-written doubly linked list?
Yes. An insertion-ordered set or map gives the same O(1) append, remove, and first-element operations. Python uses OrderedDict, Java uses LinkedHashSet, JavaScript uses Map, and Go and C# use their list types.
What if the cache must be shared by several threads?
Guard all four methods with one lock. A single operation updates several maps and buckets together, so splitting the lock can leave them inconsistent. Under the lock, each operation keeps its O(1) cost.

LFU Cache FAQ

What is the time complexity of LFU Cache?

Both get and put run in O(1) average time with frequency buckets. The brute force that scans the cache on eviction costs O(C) per put, where C is the capacity. The space is O(C) because the cache stores at most C keys.

Why use frequency buckets for LFU Cache?

Each counter changes by exactly one per use, so a key only moves between neighbouring buckets. That lets you track the minimum counter with one integer and find the victim without a scan.

Can LFU Cache be solved in O(1) extra space?

No. The cache must hold up to C keys and values, so the space is O(C). The bookkeeping adds a constant amount per stored key, so there is no way to drop below the cache's own size.

Why doesn't a heap solve LFU Cache?

A heap keyed on (counter, last use) gives O(log C) per update, because each touch changes a key's priority. The problem requires O(1) average time, so the bucket design is needed.

Is an ordered dictionary enough for the recency tie-break?

Yes, if you keep one ordered dictionary per counter value. Its insertion order gives the least recent key at the front, and removing a key from the middle is O(1).

Asked at

See which companies ask this — Pro

Practise it