Practice › Linked List
LFU Cache
Hard · Linked List · Asked at Amazon, Google, Microsoft, Uber
Simulate a least-frequently-used cache with a fixed capacity:
get k— print the value of keyk, or-1if it is not in the cache. A successful get counts as one use of the key.put k v— set the value of keyk(an update also counts as a use). Ifkis new and the cache is full, first remove the key with the fewest uses; among those, remove the least recently used one. A newly inserted key has 1 use.
Input
First line: capacity q. Next q lines: one operation each.
Output
One line per get operation.
Constraints
- 1 ≤ capacity ≤ 10^4
- 1 ≤ q ≤ 2 × 10^5
- 0 ≤ k, v ≤ 10^9
Group keys by use count, each group a doubly linked list ordered by recency, and remember the current minimum count. get/put move a key from list f to list f + 1 in O(1); eviction takes the tail of the min-count list.
Example 1
Input
2 10 put 1 1 put 2 2 get 1 put 3 3 get 2 get 3 put 4 4 get 1 get 3 get 4
Output
1 -1 3 -1 3 4
Hints
- You need the key with the smallest use count, and among those the least recently used.
- Group keys by use count; inside a group keep them in recency order (a linked list).
- Track the minimum count so eviction is O(1).
Approach
Keep value[key], count[key], and for every count f a list of keys ordered from least to most recently used (std::list with stored iterators, or a LinkedHashSet in Java, or an OrderedDict in Python). A use moves the key from list f to the back of list f + 1; if list f becomes empty and f was the minimum, the minimum becomes f + 1. A new key goes to list 1 and the minimum resets to 1. To evict, remove the front of the minimum list. Every operation is O(1).
Complexity: O(1) per operation · O(capacity) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int capacity, minF = 0;
unordered_map<long long, long long> val;
unordered_map<long long, int> cnt;
unordered_map<int, list<long long>> groups;
unordered_map<long long, list<long long>::iterator> where;
void touch(long long k) {
int f = cnt[k];
groups[f].erase(where[k]);
if (groups[f].empty()) {
groups.erase(f);
if (minF == f) minF = f + 1;
}
cnt[k] = f + 1;
groups[f + 1].push_back(k);
where[k] = prev(groups[f + 1].end());
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> capacity >> q;
string out;
while (q--) {
string op;
long long k;
cin >> op >> k;
if (op == "get") {
if (!val.count(k)) out += "-1\n";
else {
touch(k);
out += to_string(val[k]) + "\n";
}
} else {
long long v;
cin >> v;
if (val.count(k)) {
val[k] = v;
touch(k);
continue;
}
if ((int) val.size() >= capacity) {
long long old = groups[minF].front();
groups[minF].pop_front();
if (groups[minF].empty()) groups.erase(minF);
val.erase(old);
cnt.erase(old);
where.erase(old);
}
val[k] = v;
cnt[k] = 1;
groups[1].push_back(k);
where[k] = prev(groups[1].end());
minF = 1;
}
}
cout << out;
return 0;
}Python solution
import sys
from collections import OrderedDict, defaultdict
lines = sys.stdin.read().split("\n")
capacity, q = map(int, lines[0].split())
val, cnt = {}, {}
groups = defaultdict(OrderedDict) # count -> keys from least to most recently used
min_f = 0
out = []
def touch(k):
global min_f
f = cnt[k]
del groups[f][k]
if not groups[f]:
del groups[f]
if min_f == f:
min_f = f + 1
cnt[k] = f + 1
groups[f + 1][k] = None
for line in lines[1 : 1 + q]:
p = line.split()
k = int(p[1])
if p[0] == "get":
if k not in val:
out.append("-1")
else:
touch(k)
out.append(str(val[k]))
else:
v = int(p[2])
if k in val:
val[k] = v
touch(k)
continue
if len(val) >= capacity:
old, _ = groups[min_f].popitem(last=False)
if not groups[min_f]:
del groups[min_f]
del val[old], cnt[old]
val[k] = v
cnt[k] = 1
groups[1][k] = None
min_f = 1
print("\n".join(out))Java solution
import java.io.*;
import java.util.*;
public class Main {
static HashMap<Long, Long> val = new HashMap<>();
static HashMap<Long, Integer> cnt = new HashMap<>();
static HashMap<Integer, LinkedHashSet<Long>> groups = new HashMap<>();
static int minF = 0;
static void touch(long k) {
int f = cnt.get(k);
LinkedHashSet<Long> g = groups.get(f);
g.remove(k);
if (g.isEmpty()) {
groups.remove(f);
if (minF == f) minF = f + 1;
}
cnt.put(k, f + 1);
groups.computeIfAbsent(f + 1, x -> new LinkedHashSet<>()).add(k);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int capacity = Integer.parseInt(st.nextToken()), q = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
st = new StringTokenizer(br.readLine());
String op = st.nextToken();
long k = Long.parseLong(st.nextToken());
if (op.equals("get")) {
if (!val.containsKey(k)) sb.append("-1\n");
else {
touch(k);
sb.append(val.get(k)).append('\n');
}
} else {
long v = Long.parseLong(st.nextToken());
if (val.containsKey(k)) {
val.put(k, v);
touch(k);
continue;
}
if (val.size() >= capacity) {
LinkedHashSet<Long> g = groups.get(minF);
long old = g.iterator().next();
g.remove(old);
if (g.isEmpty()) groups.remove(minF);
val.remove(old);
cnt.remove(old);
}
val.put(k, v);
cnt.put(k, 1);
groups.computeIfAbsent(1, x -> new LinkedHashSet<>()).add(k);
minF = 1;
}
}
System.out.print(sb);
}
}