The LRU (Least Recently Used) Cache is implemented using a hash map (unordered_map in C++) for O(1) key-value access and a doubly-linked list to maintain the order of recently used items, where the front represents the most recently used item and the back represents the least recently used item; when the cache reaches full capacity, the least recently used item is evicted before inserting a new key-value pair, and accessing any key updates its position to the front of the list.
LRU Cache Implementation in C++ | LeetCode 146 Explained
Added:hi guys today I want to show you guys how to implement the least recently used cache in lead code in C++ um I'll be showing you guys how to use what I consider one of the fastest methods and how to implement it so yeah let's do this so they want us to implement a least recently used cache that supports two methods get which is the first method should return ne1 When the key does exist in the cache else it should return the value of the key set on the other hand should set the value of the key to the new value if exists or it inserts the value pair so the key value will be inserted into the cache if it's not present when the cache reaches full capacity it should kick out the least recently used item before inserting so yeah pretty straightforward directions so let's get to it and be using visual studio as my IDE just because it provides bug detection before I compile which is pretty helpful so as we can already see we need two data structures for this one to keep track of the um the least recently used items and want to act ASR access for the key and values so we're going to use a order map which is c++'s equivalent hash table and we're actually going to use the first parer which is a int because that's a type that's what our key type is and we're actually not going to use the in as our second parameter for Value even though it's kind of you know key value both ends we should have that but we're going to do something different we're going to call a list we're actually I'm sorry we're going to do a pair which going to contain the value and a list iterator and we'll see why later we do this C cash and we should also have a list um to store the list of keys and then we should also have a capacity to store our capacity so the aut map is going to have key value and the key iterator while on the other hand the list would just be a list of keys the first element is the most recently use and the last is the least recently used oh and we should also include the aut the map Library all right so we're going to initialize the capacity simple enough so forget there are two scenarios so we need to consider if the key exists or if it doesn't exist so if the key doesn't exist it's pretty simple we just return return negative one else if if the key does exist we we return the value so I'm going to use Auto cach find key try to find the matching value and uh if the item is not found which means that it's going to be equal to cash end then we're going to return negative 1 Auto just a lazy way for me to not have to write um our the map iterator so just if some some of you guys didn't know um so if now if the key exists we need to return the value and the value is in so we to Der reference this iterator to this order map and we're going to access the second part of the the value part of the map which is a second and to get the actual value I know it's kind confusing but to get this this is our actual value remember so we to do first oh but one thing we should know oops sorry one thing we should know that we since getting the item is considered accessing it which is also quote unquote using it we need to update our lru and for that I'm actually going to create a helper method called use and what it's going to take in as a parameter is going to take in this on order map iterator a reference sorry and here's we do so remember how we said that the first thing is the most recently used well the reason why we use a list as opposed to something like a vector is because a vector when you insert in the front is not a all at least I think it's not a all one operation because once you insert in the front you need to make sure there's space or else you have to you know resize and you also have to shift all the elements down by one so it's not the very the most efficient way to do it while as a list has all fun of inserting removal from front and back and anywhere inside the structure itself as long as you have a iterator to that node I guess what you call it so hope that explains why we using a list so so in this example how we are doing is say have a list like this one connected two connected three and two used to be the item before or the key before we accessed it so now we need to somehow get this because because um two is most recently use because that's my access so what way I'm going to do it is I'm going to delete this so these two get connected and then I'm going to push it a copy back in front and that's just going to take all one constant time so we're going to delete that right because it's going to do reference to this and it's going to delete this which is iterator pointing as a element in here and then we're going to push it to the front the new key right cuz the key is going to be here wait oh n what the heck am I doing push front and another thing we need to do is once we took out this guy right we need we this is the old key iterator we need to update this with the new key iterator to the most recent use key but since we already push it to the front we can just change this to the front of the list so going to do is Cash oops sorry right actually uh no not cach take the iterator reference to second second which is going to be this iterator here going to set equal to the first thing the list that should be it for um how wish update so before return should update this iterator nice and now that should be it for our get now for set we have a a bit more trouble if the key exists just set the value right so if so so do the same thing as we did before use the same nameing scheme find key if item exist which means that's not going to hit the and we're going to update so actually first we're going to update it first so use item and then we're going to change cash so this means that we're setting the value of the key to something else so whenever the values pair instead of writing standard pair blah blah blah blah this is a faster way for for me to construct a pair so first it takes in the value right and then takes the key iterator and the key iterator remember we know that it's the most recently use and in used we pushed it to the front so it just be the beginning of the list and uh we can technically return from here because we're done that's that's all we need to do if the key exists now if the key doesn't exist we do several things check the capacity and then use C and then um check the capacity and then we should update no actually I'm sorry not update but we should insert new key value so if the key doesn't exist um we need to check the capacity if the current size of the cache equal to you Tech greater than equal to to but um the cash should never be greater than um the capacity or else something is wrong if it's equal to capacity we need to kick out the these item and remember how our least recent used item it's in the back of the list and Al so we need to do uh you pop back but um there's a trick about cash no I mean not cash on order map you can delete a it a the element inside so you could delete this one of this by giving it the key so before we actually pop back which means we delete it from the end of our list we can we should erase it from the cache first by giving it the element in the back of the list by calling back since this will give us the key least recently used key and then we can delete that key from our list and then after we do that we need to we need to push our new key into the actually I don't know the ordering but I think you do this afterwards but I'm going to do it here you should push the key to the final list because this new pair we're going to insert it's going to be the most recently used so that also means that we need to update the value to the new one and this to one but that's not too hard because what you can do is uh going to cash insert and we're going to do the same thing we did so this is a pair and insert key we'll have another pair of value in the key erator remember how we ready to push the yeah actually yes you should do this before the insert because now since we push the key to the front of the list we know the new key iterator is going to be at the front of the list so just do again and then and uh that should be it um if you when we put on a code but for your own purpose you should always test your code so I'm do is actually I'm going to on my main to cleare out Ru cach cashal new cach going give a capacity of two and all right I'm sorry this should should be a pointer huh so now I'm going to call set one and one so here so let's keep track of this so here we'll have like one one in the cache and cash set to to oh sorry I should to reference this so now be two two and we we do something like cash C two you return this at two so let's just double check that using seter up oh okay sorry I didn't I I stream um let's check our work so out poost cash get so this should be two and then so if it if we set 3 to one here right what we should get now is we should have since two actually let's get one one so since one is the most recent access we should kick out the two in place of three CH this to three the cash get to should give us should be one because it's not going to get us anything so our expected output should be something like this one and negative 1 and let's confirm oh you guys see what happened system the system pause right so we can stop and see what happens oh hey and look we have one one which is what we expected cool and I'll highly encourage you guys to Rite some more tests but um since I'm not like going to teach you guys how to write test and like test for you guys so let's just try to actually see if it works oh hey look we got accepted guys all right I hope you guys enjoy this video and I hope it was helpful um and yeah and I'll be hopefully doing more of these videos for you guys it's good learning experience for me and yeah see you
Up Next

Database Storage Hierarchy & Buffer Management Explained
@jensdit
6.4K views•2020-11-11

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

HTTP Requests Explained: GET, POST, PUT, DELETE
@codecademy
103.1K views•2021-10-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science



























![Multithreading is the answer. What was the question? Part II - Ansel Sermersheim [ C++Now 2016 ]](https://i.ytimg.com/vi/8HBmmHUcZZA/maxresdefault.jpg)











