Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in C#: Dictionary plus List, Step by Step

Practice Read the full explanation

A cache keeps a few recent results close at hand so they are quick to read again. It can only hold a limited number of entries, so when it is full it must throw one away. An LRU (Least Recently Used) cache throws away the entry that was used longest ago. Build a class LRUCache that stores integer keys with integer values.

The class keeps: private int capacity, a Dictionary<int, int> called map (key to value) and a List<int> called order (the keys, least recently used first).

Create it: new LRUCache(capacity) makes an empty cache that holds at most capacity entries.

Methods and rules:

  • int Get(int key) returns the value stored for key. A hit counts as a use: the key becomes the most recently used. If the key is not in the cache (never stored, or already evicted), return -1 and change nothing.
  • void Put(int key, int value) stores the value for key, and the key becomes the most recently used.
    • If the key is already in the cache, replace its value. Nothing is evicted.
    • If the key is new and the cache already holds capacity entries, first evict the least recently used entry (remove it from the map and from order), then store the new one.
  • Keep order sorted by use: the least recently used key at the front, the most recently used at the end. Every use moves the key to the end.

Tools for this language:

  • The constructor public LRUCache(int capacity) saves the capacity; the fields are new Dictionary<int, int>() and new List<int>().
  • map.ContainsKey(key) tells whether a key is stored; map[key] = value stores or replaces a value; map.Remove(key) deletes an entry; map.Count counts the entries.
  • order.Remove(key) removes an item by value, order.Add(key) adds at the end, and order[0] with order.RemoveAt(0) reads and removes the first item.

This version walks over the list of keys for each operation, which is fine for learning. Interview solutions reach O(1) with a hash map plus a doubly linked list.

You start with the code that tests your class (write LRUCache above it):

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));
    }
}

Expected output:

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

Check it against the rules: Get 2 is -1 because key 2 was the least recently used when key 3 arrived (key 1 had just been read). Updating key 1 to 11 does not evict anything. With capacity 1, the second put evicts the first key.


Two structures work together: the map gives a fast lookup of the value, and order remembers which key was used when. Both must always hold the same keys.

order.Remove(key) then order.Add(key) moves a key to the end. order[0] is the least recently used key.

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);
    }
}

STEP 1 OF 19
    Ctrl + Enter to check

    C# · HASH TABLE

    Lru Cache in C#, explained

    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 most capacity entries.
    • Get(int key) returns the stored value, or -1 if 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> named map answers "is this key stored, and what is its value?" quickly.
    • A List<int> named order remembers 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.

    1. Declare the class LRUCache and close its brace right away, so every later piece goes inside it.
    2. Add the three fields: a private int capacity, a private map that starts as new Dictionary<int, int>() and a private order that starts as new List<int>(). Private means code outside the class can't change one structure without the other.
    3. Write the constructor, public LRUCache(int capacity). It has the class's name and no return type. It stores the argument with this.capacity = capacity;. The this. tells the field apart from the parameter with the same name.
    4. Write Get.
      • If map.ContainsKey(key) is false, return -1 at once. A miss touches nothing.
      • Otherwise call order.Remove(key), then order.Add(key). That moves the key to the most recently used end.
      • Return map[key].
    5. 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: read order[0] into evict, call order.RemoveAt(0), then map.Remove(evict). Removing from only one structure would break the rule that they agree.
      • After the whole if chain, run map[key] = value; and order.Add(key);. These two lines are shared by every put, new key or update, so they sit outside the branches.

    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:

    • ContainsKey before the indexer. Reading map[key] for a key that isn't there throws KeyNotFoundException. That is why Get checks ContainsKey first and returns -1 itself. Writing map[key] = value never throws: it adds the key or replaces its value, so Put needs no check there.
    • Remove and RemoveAt are different. On a List<int>, order.Remove(key) deletes the first item equal to key, and returns false if there is none. order.RemoveAt(0) deletes the item at index 0. Because the items are int, mixing them up still compiles but does the wrong thing: RemoveAt(key) treats the key as a position.
    • Dictionary.Remove takes a key and removes that entry together with its value.
    • The class has its own fields. Each new LRUCache(...) gets its own map and order, which is why the test can build the second cache s next to c without interference.
    • var in the test code lets the compiler infer the type: var c = new LRUCache(2); has type LRUCache.

    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. If Get only reads the value, a key that was just read still looks old. If it appends without removing first, the key appears twice in order. Take a variant of the class whose Get does order.Add(key) but skips order.Remove(key). With capacity 2 and the calls Put(1, 10), Put(2, 20), Get(1), its order is [1, 2, 1]. Then Put(3, 30) evicts the front key 1, even though 1 was just used, so Get(1) returns -1 while Get(2) returns 20.
    • 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, so Get(1) is 9, Get(2) is -1 and Get(3) is 3.
    • Not moving the key on an update. An update is a use. The order.Remove(key) in the first branch of Put, followed by the final order.Add(key), moves it to the end.
    • Removing from only one structure. If an eviction leaves the key in map, Get would still find the evicted key. If it leaves the key in order, a later eviction would pick a key that is no longer in the map.
    • A miss must not reorder. The early return -1 in Get comes before any change to order.
    • Capacity 0. This cache doesn't handle it. Put sees map.Count >= capacity on an empty cache, then order[0] throws ArgumentOutOfRangeException. 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, so Get(2) gives -1 and Get(1) gives 11.
    • Get(9) on a cache that never stored 9 gives -1.
    • With capacity 1, Put(1, 100) then Put(2, 200) leaves only key 2, so Get(1) is -1.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free