LRU Cache
JavaView on GFG
Time: O(1)
Space: O(capacity)
Advertisement
Intuition
Same as LeetCode 146: HashMap + doubly linked list. O(1) get and put. HashMap maps key to node; DLL maintains recency order.
Algorithm
- 1See LeetCode 146 explanation — identical structure.
Example Walkthrough
Input: capacity=2, put(1,1),put(2,2),get(1),put(3,3),get(2)
- 1.get(1)=1. After put(3): evicts key 2. get(2)=-1.
Output: get(1)=1, get(2)=-1
Common Pitfalls
- •Evict the LEAST recently used (tail node), not the least frequently used.
LRU Cache.java
Java
// Approach: HashMap + Doubly Linked List. HashMap for O(1) access; DLL for O(1) move-to-front and eviction.
// Time: O(1) Space: O(capacity)
class LRUCache {
private static int capacity;
private static LinkedHashMap<Integer, Integer> cache;
// Constructor for initializing the cache capacity with the given value.
LRUCache(int cap) {
capacity = cap;
cache = new LinkedHashMap<>(cap, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};
}
// Function to return value corresponding to the key.
public static int get(int key) {
return cache.getOrDefault(key, -1);
}
// Function for storing key-value pair.
public static void put(int key, int value) {
cache.put(key, value);
}
}
Advertisement
Was this solution helpful?