Data Structures · Visualization

LFU Cache: Put

LFU Cache

Putting a value either updates an existing key (increasing its frequency, like a get) or inserts a brand-new key with a starting frequency of 1. Time: O(1) with a proper frequency-bucket design. Space: O(1) per operation.

Big-O: get / put both O(1).

LFU Cache: Put

LFU Cache

Putting a value either updates an existing key (increasing its frequency, like a get) or inserts a brand-new key with a starting frequency of 1. If inserting a new key would exceed the cache's capacity, the item with the lowest frequency is evicted first (using recency as a tiebreaker if multiple items share the lowest frequency).

How Put Works

  1. Check if the key already exists in the hash table.
  2. If it exists, update its value and increase its frequency count (moving it to the new frequency group).
  3. If it doesn't exist and the cache is at capacity, find the group with the lowest frequency and evict its least recently used item.
  4. Insert the new key with a frequency of 1, placing it in the 'frequency 1' group.

Put Worked Example

Input: Put(3,C) on a full cache where item 2 has the lowest frequency (1)

  1. Key 3 doesn't exist and cache is full
  2. Lowest frequency group is 'frequency 1', containing item 2
  3. Evict item 2
  4. Insert item 3 with frequency 1

Output: Item 2 evicted; item 3 added with frequency 1

Try your own input
LRU — Introduction
Evicts the least-recently-used entry when the cache is full. A hash map gives O(1) lookups, while a doubly linked list tracks recency order so the oldest entry is always easy to find.
Empty cache — capacity 5
Active Value
LRU — Introduction
Press ▶ Run to watch it step by step.
Python · LRU & LFU Caches in Code
from collections import defaultdict

class LFUCache:
    def __init__(self, cap):
        self.cap = cap
        self.val = {}     # key -> value
        self.freq = {}    # key -> frequency
        self.buckets = defaultdict(dict)  # freq -> {key: None}

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

    def _bump(self, key):
        f = self.freq[key]
        del self.buckets[f][key]
        self.freq[key] = f + 1
        self.buckets[f + 1][key] = None

    def put(self, key, value):
        if self.cap == 0:
            return
        if key in self.val:
            self.val[key] = value
            self._bump(key)
            return
        if len(self.val) >= self.cap:
            # evict from the lowest-frequency bucket
            for f in sorted(self.buckets):
                if self.buckets[f]:
                    victim = next(iter(self.buckets[f]))
                    del self.buckets[f][victim]
                    del self.val[victim]
                    del self.freq[victim]
                    break
        self.val[key] = value
        self.freq[key] = 1
        self.buckets[1][key] = None
# example: put value=C
Input: Put(3,C) on a full cache where item 2 has the lowest frequency (1)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Put Time & Space Complexity

TimeO(1) with a proper frequency-bucket design
SpaceO(1) per operation

When to Use Put

  • Adding new content to a cache that prioritizes keeping consistently popular items
  • Managing limited cache space where popularity, not recency, matters most

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.