Start learning free

LESSON 86 OF 314 · HASH TABLE

LRU Cache in Go: A Map Plus a Slice of Keys

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 int, a map values map[int]int (key to value) and a slice order []int (the keys, least recently used first).

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

Methods and rules:

  • (cache *LRUCache) get(key int) int 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.
  • (cache *LRUCache) put(key int, value int) 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:

  • Go has no constructors: func newLRUCache(capacity int) *LRUCache returns a pointer to a new cache, with values: map[int]int{}.
  • Write a helper removeKey(key int) that finds the key in cache.order and cuts it out with append(cache.order[:i], cache.order[i+1:]...).
  • value, found := cache.values[key] reads a value and tells whether the key exists; cache.values[key] = value stores or replaces; delete(cache.values, key) deletes an entry; len(cache.values) counts the entries; cache.order[1:] is the slice without its 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):

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)))
}

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.

cache.removeKey(key) then cache.order = append(cache.order, key) moves a key to the end. cache.order[0] is the least recently used key.

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)
}

STEP 1 OF 26
    Ctrl + Enter to check

    GO · HASH TABLE

    Lru Cache in Go, explained

    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) int returns the stored value and makes the key the most recently used. For a missing key it returns -1 and 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

    1. Declare the struct LRUCache with the fields capacity, values and order, in that order. The slice's front is the eviction candidate.
    2. Write the constructor. Go has no constructors, so newLRUCache is an ordinary function that returns a pointer to a new struct. Set capacity and create the map with map[int]int{}. A nil map can be read but writing to it panics, so the map has to be created here. order can stay as the default empty slice.
    3. Write removeKey. Loop with for i, current := range cache.order, and when current equals key, rebuild the slice without position i by appending the part after i to the part before it. Then return, because a key appears in the slice at most once.
    4. Write get. Look the key up with value, found := cache.values[key]. On a miss, return -1 straight away so nothing changes. On a hit, call removeKey, append the key at the end, and return the value.
    5. Write put, update branch. If the key is already in the map, call removeKey. The key will be re-added at the end below, and nothing needs evicting because the entry count doesn't grow.
    6. Write put, eviction branch. Otherwise, if len(cache.values) is at least capacity, the cache is full. Read cache.order[0] into evicted, drop it from the slice with cache.order[1:], and remove it from the map with delete. Removing it from only one of the two structures would break the rule that they agree.
    7. Finish put. After the whole if chain, which runs for new keys and updates alike, store the value in the map and append the key to order.

    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 as cache.order = ... would be lost when the method returned. The constructor returns &LRUCache{...}, a pointer, so cache.put(...) works directly on it.
    • The comma-ok lookup. Reading a missing key from a map gives the zero value, 0 for an int, which is indistinguishable from a stored 0. The second result, found, is what tells a real 0 from a miss. In put, _ discards the value because only found matters, and the if statement's short form scopes found to the whole if/else if chain.
    • Cutting a slice with append. cache.order[:i] is the keys before i and cache.order[i+1:] the keys after it. append(a, b...) copies the items of b onto the end of a, and because a has 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 to cache.order and 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 later append may 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 -1 before touching order keeps 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, and len(cache.values) would stay at the capacity forever, so every later put would evict again.
    • Forgetting removeKey before the append. The key would then appear twice in order, 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 put on an empty cache runs cache.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 first put panics 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: 11 and Kept 4: 40.
    • With capacity 1, put(1, 100) then put(2, 200) makes get(1) return -1 and get(2) return 200.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free