- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 56 lines of Java from the credited upstream file 460.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class LFUCache {2 public LFUCache(int capacity) {3 this.capacity = capacity;4 }5 6 public int get(int key) {7 if (!keyToVal.containsKey(key))8 return -1;9 10 final int freq = keyToFreq.get(key);11 freqToLRUKeys.get(freq).remove(key);12 if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) {13 freqToLRUKeys.remove(freq);14 ++minFreq;15 }16 17 18 19 putFreq(key, freq + 1);20 return keyToVal.get(key);21 }22 23 public void put(int key, int value) {24 if (capacity == 0)25 return;26 if (keyToVal.containsKey(key)) {27 keyToVal.put(key, value);28 get(key); 29 return;30 }31 32 if (keyToVal.size() == capacity) {33 34 final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next();35 freqToLRUKeys.get(minFreq).remove(keyToEvict);36 keyToVal.remove(keyToEvict);37 }38 39 minFreq = 1;40 putFreq(key, minFreq); 41 keyToVal.put(key, value); 42 }43 44 private int capacity;45 private int minFreq = 0;46 private Map<Integer, Integer> keyToVal = new HashMap<>();47 private Map<Integer, Integer> keyToFreq = new HashMap<>();48 private Map<Integer, LinkedHashSet<Integer>> freqToLRUKeys = new HashMap<>();49 50 private void putFreq(int key, int freq) {51 keyToFreq.put(key, freq);52 freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>());53 freqToLRUKeys.get(freq).add(key);54 }55}56