We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard design problem, graded against 4 test cases (1 of them hidden).
Build a working data structure to an API - LRU caches, rate limiters, and iterators.
Reach for it when you see: "Design a class supporting these operations in O(1)" - an API rather than a single function.
More Designproblems →Maintain three structures:
1. `keyToVal`: key → value
2. `keyToFreq`: key → frequency count
3. `freqToList`: freq → ordered list of keys (most-recent at the head, LRU at the tail) - an OrderedDict in Python or a hash-map+doubly-linked-list pair in JS.
Plus a single integer `minFreq`.
get(key): read keyToVal; if hit, increment frequency:
- Remove key from `freqToList[oldFreq]`. If that list is empty and `oldFreq == minFreq`, increment `minFreq`.
- Append key to `freqToList[oldFreq + 1]`.
- `keyToFreq[key] = oldFreq + 1`.
put(key, val):
- If `capacity == 0`, no-op.
- If key exists: update value, then bump frequency exactly like get.
- Else: if at capacity, evict the LRU key from `freqToList[minFreq]`. Insert the new key at frequency 1, then `minFreq = 1`.
The "LRU within freq" tie-break is what an OrderedDict gives you for free.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.