← OOP

LRU Cache

Hard
Python
from collections import OrderedDict
class LRUCache:
    def __init__(self,capacity):
        self.cap=capacity; self.cache=OrderedDict()
    def get(self,key):
        if key not in self.cache: return -1
        self.cache.move_to_end(key)
        return self.cache[key]
    def put(self,key,val):
        if key in self.cache: self.cache.move_to_end(key)
        self.cache[key]=val
        if len(self.cache)>self.cap: self.cache.popitem(last=False)
Java
class LRUCache{
    int cap;
    java.util.LinkedHashMap<Integer,Integer> cache;
    LRUCache(int cap){
        this.cap=cap;
        cache=new java.util.LinkedHashMap<>(cap,0.75f,true){
            protected boolean removeEldestEntry(java.util.Map.Entry e){
                return size()>cap;
            }
        };
    }
    public int get(int key){return cache.getOrDefault(key,-1);}
    public void put(int key,int val){cache.put(key,val);}
}

Key Insight

Python OrderedDict with explicit management. Java LinkedHashMap with auto-eviction.

Python → Java Differences

  • OrderedDict vs LinkedHashMap
  • Java anonymous class override
  • Python explicit vs Java auto-eviction
Python
from collections import OrderedDict
class LRUCache:
    def __init__(self,capacity):
        self.cap=capacity; self.cache=OrderedDict()
    def get(self,key):
        if key not in self.cache: return -1
        self.cache.move_to_end(key)
        return self.cache[key]
    def put(self,key,val):
        if key in self.cache: self.cache.move_to_end(key)
        self.cache[key]=val
        if len(self.cache)>self.cap: self.cache.popitem(last=False)
Java
class LRUCache{
    int cap;
    java.util.LinkedHashMap<Integer,Integer> cache;
    LRUCache(int cap){
        this.cap=cap;
        cache=new java.util.LinkedHashMap<>(cap,0.75f,true){
            protected boolean removeEldestEntry(java.util.Map.Entry e){
                return size()>cap;
            }
        };
    }
    public int get(int key){return cache.getOrDefault(key,-1);}
    public void put(int key,int val){cache.put(key,val);}
}

Algorithm Steps

1. Ordered map for LRU
2. Move accessed to end
3. Evict oldest