You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Least Recently Used (LRU) Cache is a type of cache in which we remove the least recently used entry when the cache memory reaches its limit.
5
+
*
6
+
* For example, if a cache with a capacity to store 5 keys has the following state(arranged from most recently used key to least recently used key) -
7
+
* 5 3 2 1 4
8
+
* Now, if the next key comes as 1(which is a cache hit), then the cache state should change to -
9
+
* 1 5 3 2 4
10
+
* Now, if the next key comes as 6(which is a cache miss), then the cache state should change to -
11
+
* 6 1 5 3 2
12
+
*
13
+
* Algorithm
14
+
*
15
+
* We can use a doubly linked list of capacity (size) maintained in sorted order of access time. The most recently accessed page will be at the front of the list and the least accessed will be at the end of the list. A Hash with page number as key and address of the corresponding queue node as value.
16
+
*
17
+
* When a page is referenced, the required page may be in the memory. If it is in the memory, we need to detach the node of the list and bring it to the front of the queue.
18
+
*
19
+
* If the required page is not in the memory, we bring that in memory. In simple words, we add a new node to the front of the queue and update the corresponding node address in the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of the queue, and add the new node to the front of the queue.
20
+
*
21
+
* In Rust we can use a HashMap and a LinkedList to implement this algorithm. The HashMap will store the key-value pairs and the LinkedList will store the keys in the order of most recently used to least recently used.
22
+
*
23
+
* These handle some of the complexity of the actual implementation under the hood. For example, if there is a need for the capacity to change it will be handled by the HashMap and the LinkedList will handle the order of the keys. The HashMap will also handle the lookup of the key-value pairs.
24
+
*
25
+
* Time Complexity: O(1) for both get and put
26
+
* Space Complexity: O(capacity) where capacity is the capacity of the cache
0 commit comments