Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in Rust: HashMap Plus a Usage-Order Vec

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: usize, a HashMap<i32, i32> called cache (key to value) and a Vec<i32> called order (the keys, least recently used first).

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

Methods and rules:

  • fn get(&mut self, key: i32) -> i32 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.
  • fn put(&mut self, key: i32, value: i32) 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:

  • Rust has no constructors: fn new(capacity: i32) -> LRUCache returns a new struct (convert with capacity as usize). The methods go in an impl LRUCache block and take &mut self.
  • self.cache.contains_key(&key) tells whether a key is stored; self.cache.insert(key, value) stores or replaces a value; self.cache.remove(&key) deletes an entry; self.cache.len() counts the entries.
  • self.order.retain(|&x| x != key) removes an item by value, self.order.push(key) adds at the end, and self.order[0] with self.order.remove(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):

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

self.order.retain(|&x| x != key) then self.order.push(key) moves a key to the end. self.order[0] is the least recently used key.

struct LRUCache {
    capacity: usize,
    cache: HashMap<i32, i32>,
    order: Vec<i32>,
}
impl LRUCache {
    fn new(capacity: i32) -> LRUCache {
        LRUCache {
            capacity: capacity as usize,
            cache: HashMap::new(),
            order: Vec::new(),
        }
    }
    fn get(&mut self, key: i32) -> i32 {
        if !self.cache.contains_key(&key) {
            return -1;
        }
        self.order.retain(|&x| x != key);
        self.order.push(key);
        *self.cache.get(&key).unwrap()
    }
    fn put(&mut self, key: i32, value: i32) {
        if self.cache.contains_key(&key) {
            self.order.retain(|&x| x != key);
        } else if self.cache.len() >= self.capacity {
            let evict = self.order[0];
            self.order.remove(0);
            self.cache.remove(&evict);
        }
        self.cache.insert(key, value);
        self.order.push(key);
    }
}

STEP 1 OF 24
    Ctrl + Enter to check

    RUST · HASH TABLE

    Lru Cache in Rust, explained

    Problem overview

    An LRU (least recently used) cache holds a limited number of entries. When it is full and a new key arrives, it throws away the entry that was used longest ago. The lesson asks for a struct LRUCache that maps i32 keys to i32 values, with three pieces:

    • LRUCache::new(capacity) builds an empty cache that holds at most capacity entries.
    • get(&mut self, key) returns the stored value, or -1 if the key is absent. A hit counts as a use.
    • put(&mut self, key, value) stores a value. Updating an existing key replaces its value and evicts nothing. Adding a new key to a full cache first evicts the least recently used entry.

    The struct keeps three fields: capacity: usize, cache: HashMap<i32, i32> for the values, and order: Vec<i32> for the keys, least recently used first.

    In the lesson's test, a cache of capacity 2 receives put(1, 10) and put(2, 20), then get(1). Key 1 is now the most recent, so put(3, 30) evicts key 2, and get(2) returns -1.

    Approach: two structures that hold the same keys

    The map answers "what is the value for this key?" quickly, but it has no idea which key was touched last. The vector remembers the order but is a poor place to keep values. Using both gives each job to the structure that suits it, with one rule: they must always contain exactly the same keys. Every operation that changes one has to change the other.

    The order is a convention: the front of order (index 0) is the oldest use and the back is the newest. Marking a key as used means removing it from wherever it sits and pushing it onto the back. Evicting means taking whatever is at index 0.

    This version scans the vector for each operation, so a single call costs time proportional to the number of entries. The lesson accepts that for learning; the fully constant-time design replaces the vector with a linked structure, and is a separate exercise.

    Step by step

    The struct and its constructor

    The first steps declare the struct with its three fields, open an impl LRUCache block, and write new. Rust has no special constructor syntax: new is an ordinary function that returns a struct literal, by convention. The parameter arrives as i32 but the field is usize, so the literal converts with capacity as usize. The other two fields start as HashMap::new() and Vec::new().

    get

    A miss comes first: if the map does not contain the key, return -1 immediately and touch nothing. contains_key takes a reference, hence &key.

    On a hit, the key moves to the most recent position. retain keeps only the items for which its closure returns true, so retain(|&x| x != key) removes the key from the middle of the vector. push(key) then puts it at the back. The last line looks the value up with get(&key). That returns an Option, which is safe to unwrap here because the miss case already returned, and the * copies the number out of the reference. With no semicolon, it is the function's result.

    put

    There are three situations, and the lesson separates them with an if / else if chain:

    1. The key already exists: take it out of order with retain. The vector will get it back at the end, and the map will get the new value.
    2. The key is new and self.cache.len() >= self.capacity: read the front key into evict, remove index 0 from order, and remove evict from the map. Removing it from only one of the two would leave them out of sync.
    3. The key is new and there is room: nothing to prepare.

    After the chain, which runs for every put, the map stores the value with insert (which also replaces an existing value) and order gets the key at the back.

    The solution in Rust

    struct LRUCache {
        capacity: usize,
        cache: HashMap<i32, i32>,
        order: Vec<i32>,
    }
    impl LRUCache {
        fn new(capacity: i32) -> LRUCache {
            LRUCache {
                capacity: capacity as usize,
                cache: HashMap::new(),
                order: Vec::new(),
            }
        }
        fn get(&mut self, key: i32) -> i32 {
            if !self.cache.contains_key(&key) {
                return -1;
            }
            self.order.retain(|&x| x != key);
            self.order.push(key);
            *self.cache.get(&key).unwrap()
        }
        fn put(&mut self, key: i32, value: i32) {
            if self.cache.contains_key(&key) {
                self.order.retain(|&x| x != key);
            } else if self.cache.len() >= self.capacity {
                let evict = self.order[0];
                self.order.remove(0);
                self.cache.remove(&evict);
            }
            self.cache.insert(key, value);
            self.order.push(key);
        }
    }
    // The lesson's own test code, which comes with the starter:
    fn mainFunction() {
        let mut c = LRUCache::new(2);
        c.put(1, 10);
        c.put(2, 20);
        println!("Get 1: {}", c.get(1));
        c.put(3, 30);
        println!("Get 2: {}", c.get(2));
        println!("Get 3: {}", c.get(3));
        println!("Miss 9: {}", c.get(9));
        c.put(1, 11);
        println!("Update 1: {}", c.get(1));
        c.put(4, 40);
        println!("Evicted 3: {}", c.get(3));
        println!("Kept 1: {}", c.get(1));
        println!("Kept 4: {}", c.get(4));
        let mut s = LRUCache::new(1);
        s.put(1, 100);
        s.put(2, 200);
        println!("Small 1: {}", s.get(1));
        println!("Small 2: {}", s.get(2));
    }
    

    The mainFunction at the bottom is the lesson's test code. It prints ten lines, from Get 1: 10 to Small 2: 200, matching the rules above. A few Rust details matter here:

    • get and put both take &mut self, even get, because a read also reorders order. The variable holding the cache must therefore be declared let mut.
    • In a standalone program, HashMap comes from std::collections and needs use std::collections::HashMap; at the top.
    • The closure parameter |&x| destructures the reference that retain hands over, so x is a plain i32 that can be compared with key.
    • Inside put, let evict = self.order[0]; copies an i32, so no borrow of self.order stays alive when the next lines mutate it.

    Complexity

    With n entries in the cache, retain and remove(0) both visit or shift up to n items, so get and put take O(n) time in the worst case. The map lookups, inserts and removals are O(1) on average. Space is O(capacity): the map and the vector each hold at most capacity keys.

    Edge cases and common mistakes

    • A miss must not change anything. If get reordered keys that don't exist, the vector would contain keys the map has never heard of.
    • An update must not evict. Checking "is the cache full?" before "does the key exist?" would throw away an entry for no reason. The if / else if order avoids it.
    • Forgetting to refresh the order on a hit. Without the retain and push in get, a key that was just read could be evicted next.
    • Evicting from only one structure. The key must leave both the vector and the map.
    • Capacity 0. The lesson's tests never use it. With this code, put on a capacity-0 cache panics, because self.order[0] is out of bounds on an empty vector.

    Testing

    These are the states of order in a capacity-2 cache, for the sequence from the lesson's test:

    CallResultorder afterwards
    put(1, 10)[1]
    put(2, 20)[1, 2]
    get(1)10[2, 1]
    put(3, 30)[1, 3]
    get(2)-1[1, 3]
    get(9)-1[1, 3]
    put(1, 11)[3, 1]
    put(4, 40)[1, 4]

    After that, get(3) gives -1, get(1) gives 11 and get(4) gives 40. In a capacity-1 cache, put(1, 100) followed by put(2, 200) leaves get(1) at -1 and get(2) at 200.

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