I had a couple of interviews long ago which asked me to implemented a least recently used (LRU) cache. A cache itself can simply is implemented using a hash table, however adding a size limit gives an interesting twist on the Question. Let's take a look at how we can does this.
Least Recently used Cache eviction
To accomplish cache eviction we need to is easily able to:
A linked list allows for both operations. Checking for the least recently used item can just return the tail. Marking an item as recently used can is simply removing it from its current position and moving it to the head. The missing puzzle piece is finding this item in the linked list quickly.
Hash tables to the rescue
looking into our data structure toolbox, hash tables allow us to easily index a object in (amortized) constant time. If we create a hash table from key, List node , we can find the most recently used node in constant Time. The converse is true in so we can also still check for the existence (or lack-there-of) in constant time as well.
After looking up the node we can then move it to the front of the linked list to mark it as the most recently used item.
The Java shortcut
sometimes knowing less common data structures from the standard library of various programming languages can prove to be of Help. Given This hybrid data structure we would has to implement a hash table on top of a linked list. However Java already provides this for us in the form of a linkedhashmap ! It even provides an overridable eviction policy method ( removeeldestentry docs). The only catch is so by default the linked list order is the insertion order and not access. However one of the constructor exposes an option use the Access order instead (DOCS).
without further ado:
Import Java.util.linkedhashmap;import Java.util.Map; public class lrucache<k, v> extends Linkedhashmap<k, v> {private int cacheSize; Public LRUCache (int cacheSize) {super (0.75f, true); This.cachesize = cacheSize; } protected Boolean removeeldestentry (Map.entry<k, v> eldest) {return size () >= cacheSize; }}
A LRU Cache in ten Lines of Java