Skip to content

Commit 1de4186

Browse files
committed
Refactors more of the readme.
1 parent 6c36ae7 commit 1de4186

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

LRU Cache/Readme.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
# LRU Cache
22

3-
Caches are used to hold objects in memory. A caches size is finite; If the system doesn't have enough memory, the cache must be purged or the program will crash. [Least Recently Used][1] (LRU) is a popular algorithm in cache design. The idea is simple: In low memory situations, the oldest used member of the cache will be purged. A *priority queue* is used to enforce this behavior.
3+
Caches are used to hold objects in memory. A caches size is finite; If the system doesn't have enough memory, the cache must be purged or the program will crash. [Least Recently Used][1] (LRU) is a popular algorithm in cache design.
4+
5+
In this implementation of the LRU Cache, a size is declared during instantiation, and any insertions that go beyond the size will purge the least recently used element of the cache. A *priority queue* is used to enforce this behavior.
46

57
## The priority queue
68

79
The key to the LRU cache is the priority queue. For simplicity, you'll model the queue using a linked list. All interactions with the LRU cache should respect this queue; Calling `get` and `set` should update the priority queue to reflect the most recently accessed element.
810

11+
### Interesting tidbits
12+
913

10-
### Operations
14+
#### Adding values
1115

12-
Each time we access an element, either `set` or `get` we need to insert the element in the head of priority list. The `insert` operation will be look like this.
16+
Each time we access an element, either `set` or `get` we need to insert the element in the head of priority list. We use a helper method to handle this procedure:
1317

1418
```swift
1519
private func insert(_ key: KeyType, val: Any) {
@@ -22,7 +26,9 @@ private func insert(_ key: KeyType, val: Any) {
2226
}
2327
```
2428

25-
Each time, when we `set`, the cache size maybe already full. In this case, we need to `remove` the lowest priority node. The operation is like this.
29+
#### Purging the cache
30+
31+
When the cahce is full, a purge must take place starting with the least recently used element. In this case, we need to `remove` the lowest priority node. The operation is like this:
2632

2733
```swift
2834
private func remove(_ key: KeyType) {

0 commit comments

Comments
 (0)