Problem overview
A cache holds a limited number of entries. When it is full and a new key arrives, it must drop one entry. An LRU (Least Recently Used) cache drops the entry that was used longest ago. In this lesson you build the class LRUCache for int keys and int values.
new LRUCache(capacity)makes an empty cache that holds at mostcapacityentries.Get(int key)returns the stored value, or-1if the key is absent. A hit counts as a use, so the key becomes the most recently used. A miss changes nothing.Put(int key, int value)stores the value and makes the key the most recently used. If the key already exists, only its value is replaced. If the key is new and the cache is full, the least recently used entry is evicted first.
The lesson's own test uses capacity 2. After Put(1, 10), Put(2, 20) and Get(1), key 2 is the one used longest ago, so Put(3, 30) evicts it and Get(2) returns -1.
Approach: two structures that always agree
The cache has two jobs, and one structure does each job well.
- A
Dictionary<int, int>namedmapanswers "is this key stored, and what is its value?" quickly. - A
List<int>namedorderremembers recency. It holds the keys with the least recently used at the front (index 0) and the most recently used at the end.
The dictionary has no notion of "oldest", and the list is slow for lookups, so the class keeps both. The rule that makes it work is that both always hold exactly the same keys. Every change to one is mirrored in the other. Whenever a key is used, it is taken out of order and added again at the end.
This version walks over the list for each operation, which is fine for learning. The faster designs replace the list with a doubly linked list so that moving a key costs constant time. Here the goal is to get the bookkeeping right first.
Tracing the lesson's example
Here is order after each operation for capacity 2, copied from a run of the solution below:
Put(1, 10) [1]
Put(2, 20) [1, 2]
Get(1) [2, 1]
Put(3, 30) [1, 3]
Get(2) -1 [1, 3]
Put(1, 11) [3, 1]
After Get(1) the key 1 sits at the end, so key 2 is at the front. Put(3, 30) finds the cache full, evicts the front key 2 and appends 3. The last line is an update: key 1 moves to the end and nothing is evicted.
Step by step
The lesson builds the class in 19 small steps. They fall into five groups.
- Declare the class
LRUCacheand close its brace right away, so every later piece goes inside it. - Add the three fields: a private
int capacity, a privatemapthat starts asnew Dictionary<int, int>()and a privateorderthat starts asnew List<int>(). Private means code outside the class can't change one structure without the other. - Write the constructor,
public LRUCache(int capacity). It has the class's name and no return type. It stores the argument withthis.capacity = capacity;. Thethis.tells the field apart from the parameter with the same name. - Write
Get.- If
map.ContainsKey(key)is false, return-1at once. A miss touches nothing. - Otherwise call
order.Remove(key), thenorder.Add(key). That moves the key to the most recently used end. - Return
map[key].
- If
- Write
Put.- If the key is already in the map, take it out of
order. An update needs no room, so nothing is evicted. - Otherwise, if
map.Count >= capacity, the cache is full: readorder[0]intoevict, callorder.RemoveAt(0), thenmap.Remove(evict). Removing from only one structure would break the rule that they agree. - After the whole
ifchain, runmap[key] = value;andorder.Add(key);. These two lines are shared by every put, new key or update, so they sit outside the branches.
- If the key is already in the map, take it out of
The solution in C#
class LRUCache {
private int capacity;
private Dictionary<int, int> map = new Dictionary<int, int>();
private List<int> order = new List<int>();
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int Get(int key) {
if (!map.ContainsKey(key)) return -1;
order.Remove(key);
order.Add(key);
return map[key];
}
public void Put(int key, int value) {
if (map.ContainsKey(key)) {
order.Remove(key);
} else if (map.Count >= capacity) {
int evict = order[0];
order.RemoveAt(0);
map.Remove(evict);
}
map[key] = value;
order.Add(key);
}
}
class Solution {
public void MainFunction() {
var c = new LRUCache(2);
c.Put(1, 10);
c.Put(2, 20);
Console.WriteLine("Get 1: " + c.Get(1));
c.Put(3, 30);
Console.WriteLine("Get 2: " + c.Get(2));
Console.WriteLine("Get 3: " + c.Get(3));
Console.WriteLine("Miss 9: " + c.Get(9));
c.Put(1, 11);
Console.WriteLine("Update 1: " + c.Get(1));
c.Put(4, 40);
Console.WriteLine("Evicted 3: " + c.Get(3));
Console.WriteLine("Kept 1: " + c.Get(1));
Console.WriteLine("Kept 4: " + c.Get(4));
var s = new LRUCache(1);
s.Put(1, 100);
s.Put(2, 200);
Console.WriteLine("Small 1: " + s.Get(1));
Console.WriteLine("Small 2: " + s.Get(2));
}
}
The class Solution with MainFunction is the lesson's test code. It prints the ten lines the lesson expects:
Get 1: 10
Get 2: -1
Get 3: 30
Miss 9: -1
Update 1: 11
Evicted 3: -1
Kept 1: 11
Kept 4: 40
Small 1: -1
Small 2: 200
C# details worth knowing:
ContainsKeybefore the indexer. Readingmap[key]for a key that isn't there throwsKeyNotFoundException. That is whyGetchecksContainsKeyfirst and returns-1itself. Writingmap[key] = valuenever throws: it adds the key or replaces its value, soPutneeds no check there.RemoveandRemoveAtare different. On aList<int>,order.Remove(key)deletes the first item equal tokey, and returnsfalseif there is none.order.RemoveAt(0)deletes the item at index 0. Because the items areint, mixing them up still compiles but does the wrong thing:RemoveAt(key)treats the key as a position.Dictionary.Removetakes a key and removes that entry together with its value.- The class has its own fields. Each
new LRUCache(...)gets its ownmapandorder, which is why the test can build the second cachesnext tocwithout interference. varin the test code lets the compiler infer the type:var c = new LRUCache(2);has typeLRUCache.
Complexity
Time: O(n) per operation, where n is the number of entries in the cache (at most capacity). The dictionary checks (ContainsKey, the indexer, Remove) take constant time on average. List.Remove(key) has to search for the key, and both it and RemoveAt(0) shift the items after the removed one, so each takes time proportional to the list's length. Appending with Add is cheap.
Space: O(capacity). The map and the list each hold at most capacity keys.
Edge cases and common mistakes
- Forgetting to move the key in
Get. IfGetonly reads the value, a key that was just read still looks old. If it appends without removing first, the key appears twice inorder. Take a variant of the class whoseGetdoesorder.Add(key)but skipsorder.Remove(key). With capacity 2 and the callsPut(1, 10),Put(2, 20),Get(1), itsorderis[1, 2, 1]. ThenPut(3, 30)evicts the front key 1, even though 1 was just used, soGet(1)returns-1whileGet(2)returns20. - Evicting on an update. Updating an existing key must not evict anything, even when the cache is full. With capacity 2,
Put(1, 1),Put(2, 2),Put(1, 9)keeps both keys;Put(3, 3)then evicts key 2, soGet(1)is9,Get(2)is-1andGet(3)is3. - Not moving the key on an update. An update is a use. The
order.Remove(key)in the first branch ofPut, followed by the finalorder.Add(key), moves it to the end. - Removing from only one structure. If an eviction leaves the key in
map,Getwould still find the evicted key. If it leaves the key inorder, a later eviction would pick a key that is no longer in the map. - A miss must not reorder. The early
return -1inGetcomes before any change toorder. - Capacity 0. This cache doesn't handle it.
Putseesmap.Count >= capacityon an empty cache, thenorder[0]throwsArgumentOutOfRangeException. The lesson's tests use capacities of 1 and above.
Testing
Try these in the editor above, using capacity 2:
Put(1, 10),Put(2, 20),Get(1),Put(3, 30),Get(2)gives-1, because key 2 was the least recently used.Put(1, 10),Put(2, 20),Put(1, 11),Put(3, 30): key 2 is evicted, soGet(2)gives-1andGet(1)gives11.Get(9)on a cache that never stored 9 gives-1.- With capacity 1,
Put(1, 100)thenPut(2, 200)leaves only key 2, soGet(1)is-1.
