LRU Cache
Intro
A LRU cache is "a cache with a fixed maximum size, evicting items that were used least-recently".
Question (LC.146)
LRU supports two regular hash operations - get(key) and put(key, value). But the cache will operate under a limited capacity. The least recently used item will be deleted when running out of space.
Analysis
This is a cache data structure, we should keep get and put in O(1) time. We'll need a HashMap internally.
Q1: How to keep track of the recentness?
We want to keep the pairs in a relative order. We also want insert/delete to be O(1) so linked list!!
Q2: How do we implement insert/delete? Do we need a DLL?
A DDL will make deletion a lot easier b/c you have the reference to the previous node. But then a SLL can just get a ref to the previous node then perform the same action.
Using Java Build-in API
From Java doc, LinkedHashMap is a "Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries."
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.DLL Implementation
Reference
Java Doc LinkedHashMap
Twitter API DOCs LRUCache
Last updated