Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in TypeScript: Map plus an Order Array

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: capacity: number, a Map<number, number> called map (key to value) and a number[] 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:

  • get(key: number): number 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.
  • put(key: number, value: number): void 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:

  • In constructor(capacity: number), save this.capacity; declare the typed fields map: Map<number, number> = new Map() and order: number[] = [].
  • this.map.has(key) tells whether a key is stored; this.map.set(key, value) stores or replaces a value; this.map.delete(key) deletes an entry; this.map.size counts the entries.
  • this.order.filter((k) => k !== key) builds an array without the key, push(key) adds at the end, and shift() removes and returns 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):

let c = new LRUCache(2);
c.put(1, 10);
c.put(2, 20);
console.log("Get 1: " + c.get(1));
c.put(3, 30);
console.log("Get 2: " + c.get(2));
console.log("Get 3: " + c.get(3));
console.log("Miss 9: " + c.get(9));
c.put(1, 11);
console.log("Update 1: " + c.get(1));
c.put(4, 40);
console.log("Evicted 3: " + c.get(3));
console.log("Kept 1: " + c.get(1));
console.log("Kept 4: " + c.get(4));
let s = new LRUCache(1);
s.put(1, 100);
s.put(2, 200);
console.log("Small 1: " + s.get(1));
console.log("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.

this.order = this.order.filter((k) => k !== key) then this.order.push(key) moves a key to the end. this.order.shift()! gives the least recently used key.

class LRUCache {
    capacity: number;
    map: Map<number, number> = new Map();
    order: number[] = [];

    constructor(capacity: number) {
        this.capacity = capacity;
    }

    get(key: number): number {
        if (!this.map.has(key)) return -1;
        this.order = this.order.filter((k) => k !== key);
        this.order.push(key);
        return this.map.get(key)!;
    }

    put(key: number, value: number): void {
        if (this.map.has(key)) {
            this.order = this.order.filter((k) => k !== key);
        } else if (this.map.size >= this.capacity) {
            const evict = this.order.shift()!;
            this.map.delete(evict);
        }
        this.map.set(key, value);
        this.order.push(key);
    }
}

STEP 1 OF 18
    Ctrl + Enter to check

    TYPESCRIPT · HASH TABLE

    Lru Cache in TypeScript, explained

    Problem overview

    A cache holds a limited number of recent results. When it is full and a new key arrives, it must drop something. An LRU (Least Recently Used) cache drops the entry that was used longest ago. The lesson asks for a class LRUCache with integer keys and integer values, built from three fields: capacity (a number), map (a Map<number, number> from key to value) and order (a number[] of keys, least recently used first).

    The class has two methods:

    • get(key) returns the stored value and marks the key as the most recently used. For a key that isn't stored it returns -1 and changes nothing.
    • put(key, value) stores the value and marks the key as the most recently used. Replacing the value of an existing key evicts nothing. A new key arriving in a full cache first evicts the least recently used key.

    Take a cache of capacity 2. After put(1, 10) and put(2, 20), order is [1, 2]. Calling get(1) returns 10 and moves key 1 to the end, so order becomes [2, 1]. Now put(3, 30) finds the cache full and evicts the front key, 2, leaving order as [1, 3]. A later get(2) returns -1.

    Approach: two structures, one invariant

    Each structure does the job it is good at. The Map answers "is this key stored, and what is its value?" quickly. The array answers "which key is the oldest?" by position: the front is the least recently used key and the end is the most recently used one. Every use takes the key out of its place and pushes it at the end.

    The one rule to protect is that map and order always contain the same keys. Whenever you add or remove a key in one, you do the same in the other.

    This version searches the array on every use, which takes time proportional to the number of stored keys. That is fine for learning the behaviour. A cache that does every operation in constant time combines a hash map with a doubly linked list instead; this lesson builds the simpler array version.

    Step by step

    1. Declare the class and its closing brace. Everything else goes inside.
    2. Add the three fields. capacity is a number that the constructor fills in. map starts as an empty Map and order as an empty array, so a new cache is empty without any constructor code for them.
    3. Write the constructor and save its argument in this.capacity.
    4. Start get with the miss case. If the map doesn't have the key, return -1 immediately. A miss must not touch order.
    5. Move the key to the end. Rebuild this.order with filter, keeping every key except this one, then push the key. The key is now the most recently used.
    6. Return the value from the map.
    7. Start put with the update case. If the map already has the key, take it out of order with the same filter. The size doesn't change, so nothing is evicted.
    8. Add the eviction case as an else if: the key is new and this.map.size is already at least this.capacity. Remove the first key of order with shift(), and delete that key from the map too. Removing it from only one structure would break the rule above.
    9. After the whole if chain, store the value in the map and push the key at the end of order. This runs for every put, new key or update, which is why it sits outside the branches.

    The solution in TypeScript

    class LRUCache {
        capacity: number;
        map: Map<number, number> = new Map();
        order: number[] = [];
    
        constructor(capacity: number) {
            this.capacity = capacity;
        }
    
        get(key: number): number {
            if (!this.map.has(key)) return -1;
            this.order = this.order.filter((k) => k !== key);
            this.order.push(key);
            return this.map.get(key)!;
        }
    
        put(key: number, value: number): void {
            if (this.map.has(key)) {
                this.order = this.order.filter((k) => k !== key);
            } else if (this.map.size >= this.capacity) {
                const evict = this.order.shift()!;
                this.map.delete(evict);
            }
            this.map.set(key, value);
            this.order.push(key);
        }
    }
    
    let c = new LRUCache(2);
    c.put(1, 10);
    c.put(2, 20);
    console.log("Get 1: " + c.get(1));
    c.put(3, 30);
    console.log("Get 2: " + c.get(2));
    console.log("Get 3: " + c.get(3));
    console.log("Miss 9: " + c.get(9));
    c.put(1, 11);
    console.log("Update 1: " + c.get(1));
    c.put(4, 40);
    console.log("Evicted 3: " + c.get(3));
    console.log("Kept 1: " + c.get(1));
    console.log("Kept 4: " + c.get(4));
    let s = new LRUCache(1);
    s.put(1, 100);
    s.put(2, 200);
    console.log("Small 1: " + s.get(1));
    console.log("Small 2: " + s.get(2));
    

    TypeScript details

    • Field initializers. map: Map<number, number> = new Map() declares the field's type and gives it a starting value in one line. The constructor only has to deal with capacity.
    • The ! after get and shift(). Map.get is typed as returning number | undefined, and so is shift(). The trailing ! tells the compiler you know the value is there. It is only a type annotation: it is erased when the code compiles to JavaScript and checks nothing at run time. Here it is true, because get already checked has(key) and an eviction only happens when the map holds entries.
    • filter returns a new array. That is why the result is assigned back to this.order. Calling this.order.filter(...) without the assignment would change nothing.
    • Map size. this.map.size is a property, not a method, so there are no parentheses.

    Complexity

    With n keys stored, has, set and delete on the Map are constant time on average. The filter call visits every key, so get and an update in put take O(n) time. shift() also has to move the remaining items, so an eviction is O(n) as well. The space is O(capacity): the map and the array each hold at most that many keys.

    Edge cases and common mistakes

    • Reading a key must refresh it. In the example, key 2 is evicted because get(1) made key 1 the more recent one. Skipping the move in get would evict key 1 instead.
    • Updating an existing key must not evict. If the size check ran before the has check, a full cache would throw away an entry just to replace a value. The if/else if order avoids it.
    • Forgetting to delete from the map. Shifting the key out of order but not out of map leaves a stale value that get keeps returning, and the map grows past its capacity.
    • Duplicate keys in order. Pushing a key without first removing its old position makes the array longer than the map and ruins the eviction order.
    • A miss changes nothing. get(9) on a missing key returns -1 and leaves order as it was.
    • Capacity 0. The class assumes a capacity of at least 1. With capacity 0, put on an empty cache has nothing to evict, so shift() gives undefined and the entry is stored anyway. The lesson's tests use capacities 1 and 2.

    Testing

    Try these in the editor above. With capacity 1, put(1, 100) then put(2, 200) evicts key 1, so get(1) is -1 and get(2) is 200. With capacity 2, after put(1, 10), put(2, 20), get(1) and put(3, 30), get(2) is -1 while get(3) is 30.

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free