Problem overview
A cache holds a limited number of entries. When it is full and a new key arrives, it must drop one entry to make room. An LRU (Least Recently Used) cache drops the entry that was used longest ago. Reading a key and writing a key both count as a use.
The lesson asks for a type LRUCache with three fields: capacity (an int), values (a map[int]int from key to value) and order (a []int of keys, least recently used first). You write a constructor newLRUCache(capacity int) *LRUCache and two methods:
get(key int) intreturns the stored value and makes the key the most recently used. For a missing key it returns-1and changes nothing.put(key int, value int)stores a value and makes the key the most recently used. If the key is new and the cache is full, the least recently used key is evicted first. If the key already exists, only its value is replaced and nothing is evicted.
The test code builds a cache of capacity 2, puts keys 1 and 2, reads key 1, then puts key 3. Key 2 is now the least recently used, so it is evicted and get(2) gives -1, while get(3) gives 30.
Approach: two structures that always agree
The map answers "is this key here, and what is its value?" quickly. It cannot say which key is the oldest, because a Go map has no order, and iterating over it visits keys in random order. So a second structure, the slice order, records the recency: the front is the next key to evict and the back is the key used last.
The one rule that keeps everything correct is that the map and the slice hold exactly the same set of keys after every call. Each operation then does two things: update the map as needed, and move the touched key to the back of the slice.
Moving a key to the back takes two moves: cut it out of wherever it sits, then append it at the end. A small helper, removeKey, does the cutting, since Go slices have no built-in remove.
This version scans the slice to find a key, so a use costs time proportional to the number of entries. That is fine for learning. A hash map combined with a doubly linked list removes the scan and makes every operation constant time, but this lesson keeps the simple slice.
Step by step
- Declare the struct
LRUCachewith the fieldscapacity,valuesandorder, in that order. The slice's front is the eviction candidate. - Write the constructor. Go has no constructors, so
newLRUCacheis an ordinary function that returns a pointer to a new struct. Setcapacityand create the map withmap[int]int{}. A nil map can be read but writing to it panics, so the map has to be created here.ordercan stay as the default empty slice. - Write
removeKey. Loop withfor i, current := range cache.order, and whencurrentequalskey, rebuild the slice without positioniby appending the part afterito the part before it. Thenreturn, because a key appears in the slice at most once. - Write
get. Look the key up withvalue, found := cache.values[key]. On a miss, return-1straight away so nothing changes. On a hit, callremoveKey, append the key at the end, and return the value. - Write
put, update branch. If the key is already in the map, callremoveKey. The key will be re-added at the end below, and nothing needs evicting because the entry count doesn't grow. - Write
put, eviction branch. Otherwise, iflen(cache.values)is at leastcapacity, the cache is full. Readcache.order[0]intoevicted, drop it from the slice withcache.order[1:], and remove it from the map withdelete. Removing it from only one of the two structures would break the rule that they agree. - Finish
put. After the wholeifchain, which runs for new keys and updates alike, store the value in the map and append the key toorder.
The solution in Go
type LRUCache struct {
capacity int
values map[int]int
order []int
}
func newLRUCache(capacity int) *LRUCache {
return &LRUCache{capacity: capacity, values: map[int]int{}}
}
func (cache *LRUCache) removeKey(key int) {
for i, current := range cache.order {
if current == key {
cache.order = append(cache.order[:i], cache.order[i+1:]...)
return
}
}
}
func (cache *LRUCache) get(key int) int {
value, found := cache.values[key]
if !found {
return -1
}
cache.removeKey(key)
cache.order = append(cache.order, key)
return value
}
func (cache *LRUCache) put(key int, value int) {
if _, found := cache.values[key]; found {
cache.removeKey(key)
} else if len(cache.values) >= cache.capacity {
evicted := cache.order[0]
cache.order = cache.order[1:]
delete(cache.values, evicted)
}
cache.values[key] = value
cache.order = append(cache.order, key)
}
func mainFunction() {
cache := newLRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
fmt.Println("Get 1: " + strconv.Itoa(cache.get(1)))
cache.put(3, 30)
fmt.Println("Get 2: " + strconv.Itoa(cache.get(2)))
fmt.Println("Get 3: " + strconv.Itoa(cache.get(3)))
fmt.Println("Miss 9: " + strconv.Itoa(cache.get(9)))
cache.put(1, 11)
fmt.Println("Update 1: " + strconv.Itoa(cache.get(1)))
cache.put(4, 40)
fmt.Println("Evicted 3: " + strconv.Itoa(cache.get(3)))
fmt.Println("Kept 1: " + strconv.Itoa(cache.get(1)))
fmt.Println("Kept 4: " + strconv.Itoa(cache.get(4)))
small := newLRUCache(1)
small.put(1, 100)
small.put(2, 200)
fmt.Println("Small 1: " + strconv.Itoa(small.get(1)))
fmt.Println("Small 2: " + strconv.Itoa(small.get(2)))
}
The mainFunction at the bottom is the lesson's test code. It stays below your class.
The Go details worth a closer look:
- Pointer receivers. The methods take
cache *LRUCache, so they modify the cache the caller holds. With a value receiver, each method would work on a copy, and an assignment such ascache.order = ...would be lost when the method returned. The constructor returns&LRUCache{...}, a pointer, socache.put(...)works directly on it. - The comma-ok lookup. Reading a missing key from a map gives the zero value,
0for anint, which is indistinguishable from a stored 0. The second result,found, is what tells a real 0 from a miss. Input,_discards the value because onlyfoundmatters, and theifstatement's short form scopesfoundto the wholeif/else ifchain. - Cutting a slice with
append.cache.order[:i]is the keys beforeiandcache.order[i+1:]the keys after it.append(a, b...)copies the items ofbonto the end ofa, and becauseahas spare capacity, the copy happens inside the same backing array, shifting the tail one place left. That is safe here because the result is assigned straight back tocache.orderand the loop returns right after. - Dropping the front.
cache.order[1:]shares the same backing array and just starts one item later. It costs no copying. A laterappendmay allocate a new array when the capacity runs out. - Methods on a struct. Go has no classes. The struct holds the data, and the functions with a receiver in front of the name act as its methods.
Tracing the lesson's test
Running the test sequence and printing order after some steps shows how the two structures move together:
after put(1,10), put(2,20): order [1 2]
after get(1) -> 10: order [2 1]
after put(3,30): order [1 3] values map[1:10 3:30]
get(2) -> -1, get(3) -> 30: order [1 3]
after put(1,11): order [3 1] values map[1:11 3:30]
after put(4,40): order [1 4] values map[1:11 4:40]
Reading key 1 moved it behind key 2, so putting key 3 evicted key 2. Updating key 1 to 11 evicted nothing but moved it to the back, so putting key 4 evicted key 3.
Complexity
Time: map reads and writes take constant time on average. removeKey scans order, so it takes O(n) for n entries, and both get (on a hit) and put (on an update) call it. Evicting from the front is constant. So get and put are O(n) in the worst case, where n is at most the capacity.
Space: O(capacity). The map and the slice each hold at most capacity keys.
Edge cases and common mistakes
- A miss must not change anything. Returning
-1before touchingorderkeeps a failed lookup from disturbing the recency list. - Updating an existing key. It must not evict. In a full cache of capacity 2 holding keys 1 and 3,
put(1, 11)keeps both keys and only moves 1 to the back. - Forgetting to refresh recency on
get. Without the move to the back, key 2 would not be the first to go in the test above. - Evicting from the slice but not the map. The old key would stay readable through
get, andlen(cache.values)would stay at the capacity forever, so every laterputwould evict again. - Forgetting
removeKeybefore the append. The key would then appear twice inorder, and the stale copy at the front would later evict a key that was used recently. - Capacity 0. The lesson assumes at least 1. With capacity 0, a
puton an empty cache runscache.order[0]on an empty slice and panics with an index out of range error. - Using the zero map. A struct built without
values: map[int]int{}has a nil map, and the firstputpanics on the assignment.
Testing
- The lesson's test prints
Get 1: 10,Get 2: -1,Get 3: 30,Miss 9: -1,Update 1: 11,Evicted 3: -1,Kept 1: 11andKept 4: 40. - With capacity 1,
put(1, 100)thenput(2, 200)makesget(1)return-1andget(2)return200.
