Start learning free

LESSON 368 OF 671 · HASH TABLE

LRU Cache in JavaScript: a Map plus a Usage-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, a Map called map (key to value) and an array 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) 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, 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:

  • In constructor(capacity), save this.capacity; declare the fields map = new Map() and order = [].
  • 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;
    map = new Map();
    order = [];

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

    get(key) {
        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, value) {
        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

    JAVASCRIPT · HASH TABLE

    Lru Cache in JavaScript, explained

    Problem overview

    A cache keeps a few recent results close at hand, and it can only hold a limited number of entries. An LRU (Least Recently Used) cache handles a full cache by throwing away the entry that was used longest ago. The lesson asks for a class LRUCache that stores integer keys with integer values.

    new LRUCache(capacity) makes an empty cache. get(key) returns the stored value, or -1 when the key is missing, and a hit counts as a use. put(key, value) stores a value, and the key becomes the most recently used. Putting an existing key only replaces its value. Putting a new key into a full cache first evicts the least recently used entry.

    The example uses a cache of capacity 2. After put(1, 10) and put(2, 20), reading key 1 makes key 2 the oldest. Then put(3, 30) evicts key 2, so get(2) returns -1 while keys 1 and 3 are still there.

    Approach: two structures that always hold the same keys

    The class keeps two fields. A Map called map answers "is this key stored, and what is its value?" quickly. An array called order remembers when each key was used: the least recently used key sits at the front and the most recently used at the end. Every use moves a key to the end, so the front is always the next one to evict.

    The two fields must describe the same set of keys. Every change to one needs a matching change to the other: removing a key from order without deleting it from the map leaves a value that can never be evicted, and the other way round leaves a key that order doesn't know about.

    This version scans order on every operation, so each get and put costs time proportional to the number of stored keys. That is fine for learning the rules. Solutions that need constant time per operation combine a hash map with a doubly linked list instead.

    Step by step

    1. Declare the class and close its brace at once, so every later step has a place to go.
    2. Add the capacity field. A class field declared in the body, with no value yet. The constructor fills it in.
    3. Add map, a field that starts as an empty Map.
    4. Add order, a field that starts as an empty array.
    5. Write the constructor with one parameter and save it in this.capacity.
    6. Start get(key). On a miss, return -1 immediately, with no change to order, since a miss is not a use.
    7. On a hit, move the key to the end. First rebuild this.order with filter, keeping every key that is not this one. Then push the key back on the end.
    8. Return the stored value with this.map.get(key).
    9. Start put(key, value) with the update case. If the map already has the key, take the key out of order with the same filter. Nothing is evicted, because an update takes no new room.
    10. Add the eviction case as an else if: the key is new and this.map.size is at least this.capacity. Use shift() to remove the front key of order, and delete that key from the map too.
    11. Store the value after the whole if chain, because both new keys and updates need it.
    12. Push the key onto the end of order, again for both cases.

    The solution in JavaScript

    class LRUCache {
        capacity;
        map = new Map();
        order = [];
    
        constructor(capacity) {
            this.capacity = capacity;
        }
    
        get(key) {
            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, value) {
            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));

    Everything above the line let c = new LRUCache(2); is the class. The rest is the lesson's test code, which prints ten lines:

    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

    Language details

    • Lines such as capacity; and map = new Map(); in the class body are class fields. Each instance gets its own Map and its own array, because the initialisers run once per new.
    • filter returns a new array, so the result must be assigned back to this.order. Calling this.order.filter(...) alone changes nothing.
    • shift() removes and returns the first element, and on an empty array it returns undefined.
    • A Map compares keys by identity for objects and by value for numbers, so 1 and "1" are different keys. The test code only uses numbers.
    • get returns -1 for a miss, so a stored value of -1 would look like a miss. The lesson stores non-negative values only.

    Tracing the state

    Printing order after each call on a cache of capacity 2 shows how the two structures move together:

    put(1, 10) -> order: [1], map size: 1
    put(2, 20) -> order: [1,2], map size: 2
    10
    get(1) -> order: [2,1], map size: 2
    put(3, 30) -> order: [1,3], map size: 2
    -1
    get(2) -> order: [1,3], map size: 2
    put(1, 11) -> order: [3,1], map size: 2

    After get(1), key 1 moved behind key 2. So put(3, 30) evicted key 2, the front of order. The miss on key 2 left order alone, and updating key 1 moved it to the end without evicting anything.

    Complexity

    Each get and put runs filter over order, which holds at most capacity keys, so an operation takes O(capacity) time. The Map operations are constant time on average, and shift() on an array moves the remaining elements, which is also linear in the worst case. Space is O(capacity): the map and the array each hold at most that many keys.

    Edge cases and common mistakes

    • Forgetting that a hit is a use. If get doesn't move the key, the wrong entry is evicted. In the example, key 2 is evicted only because key 1 was just read.
    • Evicting on an update. A full cache must not drop anything when the key is already present, which is why the update case comes first in the if chain.
    • Capacity 1. Every new key evicts the previous one, as the last two test lines show.
    • Capacity 0. The class has no special case for it. With new LRUCache(0), put(1, 5) evicts nothing useful (the empty order gives undefined) and still stores the key, so get(1) returns 5. The lesson doesn't test this case.
    • Letting the structures drift apart. Update map and order together on every path.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free