Here's how to wire up the maps and the minFreq tracker. Each frequency bucket is an ordered dictionary so removals and insertions are .
class LFUCache:
initialize(capacity):
this.capacity = capacity
this.minFreq = 0
this.keyToVal = {}
this.keyToFreq = {}
this.freqToKeys = {}
get(key):
if key not in keyToVal:
return -1
freq = keyToFreq[key]
remove key from freqToKeys[freq]
if freqToKeys[freq] is empty and freq == minFreq:
minFreq = freq + 1
freq = freq + 1
keyToFreq[key] = freq
add key to end of freqToKeys[freq]
return keyToVal[key]
put(key, value):
if capacity == 0:
return
if key in keyToVal:
keyToVal[key] = value
get(key)
return
if size(keyToVal) == capacity:
evictKey = remove first from freqToKeys[minFreq]
delete keyToVal[evictKey]
delete keyToFreq[evictKey]
keyToVal[key] = value
keyToFreq[key] = 1
add key to end of freqToKeys[1]
minFreq = 1