Monday, December 26, 2011

LRU Cache Design

Q. How to design an LRU cache with the constraint that the LRU element should be obtained in 0(1) runtime.

A. I started off to use heap to store the hits and use the hits count to find LRU elements. It achieves all the requirements posed in the question. But every insertion and deletion from the heap involves 0(logn) complexity. There is a more optimal approach to this problem. The question has no requirement to have all the hits maintained.

We can leverage on the standard Java Collections Map and implement the LRU cache the below way. The crux is that we use a doubly linked list, a collection to store the access order of the elements in the cache. Whenever a key is accessed, it is moved to the top of the list.


Class LRUCache<K,V> {
Map<K, NodeEntry<V> > cache;
List<NodeEntry<V>> accessOrderList;

public V find(K key){
LRUNode nodeEntry = cache.get(key) ;
if( nodeEntry == null) { return null; }
accessOrderList.moveToTop( nodeEntry );
}
};