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 mostcapacityentries.get(&mut self, key)returns the stored value, or-1if 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:
- The key already exists: take it out of
orderwithretain. The vector will get it back at the end, and the map will get the new value. - The key is new and
self.cache.len() >= self.capacity: read the front key intoevict, remove index 0 fromorder, and removeevictfrom the map. Removing it from only one of the two would leave them out of sync. - 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:
getandputboth take&mut self, evenget, because a read also reordersorder. The variable holding the cache must therefore be declaredlet mut.- In a standalone program,
HashMapcomes fromstd::collectionsand needsuse std::collections::HashMap;at the top. - The closure parameter
|&x|destructures the reference thatretainhands over, soxis a plaini32that can be compared withkey. - Inside
put,let evict = self.order[0];copies ani32, so no borrow ofself.orderstays 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
getreordered 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 iforder avoids it. - Forgetting to refresh the order on a hit. Without the
retainandpushinget, 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,
puton a capacity-0 cache panics, becauseself.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:
| Call | Result | order 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.
