LRU Approximation (Second Chance Algorithm)
If you are not familiar with Least Recently Used Algorithm, check Least Recently Used Algorithm(Page Replacement)
This algorithm is a combination of using a queue, similar to FIFO (FIFO (Page Replacement)) alongside using an array to keep track of the bits used to give the queued page a “second chance”.
How does the algorithm work:
- Set all the values of the bitref as False (Let it be the size of max capacity of queue).
- Set an empty queue to have a max capacity.
- Check if the queue is not full:
- If the element is in the queue, set its corresponding bitref = 1.
- If the element is not in the queue, then push it into the queue.
- If the queue is full:
- Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.
- Remove that element from the queue.
- Push the current element from the input array into the queue.
The bits are set as usual in this case to one for the indices in the bitref until the queue is full.
Once the queue becomes full, according to FIFO Page Replacement Algorithm, we should get rid of the front of the queue (if the element is a fault/miss). But here we don’t do that.
Instead we first check its reference bit (aka bitref) if its 0 or 1 (False or True). If it is 0 (false), we pop it from the queue and push the waiting element into the queue. But if it is 1 (true), we then set its reference bit (bitref) to 0 and move it to the back of the queue. We keep on doing this until we come across the front of the queue to have its front value’s reference bit (bitref) as 0 (false).
Then we follow the usual by removing it from the queue and pushing the waiting element into the queue.
What if the waiting element is in the queue already? We just set its reference bit (bitref) to 1 (true).
We now move all the values like 2, 4, 1 to the back until we encounter 3, whose bitref is 0. While moving 2, 4, 1 to the back, we set their bitref values to 0.
So now, the question how is this an approximation of LRU, when it clearly implements FIFO instead of LRU. Well, this works by giving a second chance to the front of the queue (which in FIFO‘s case would have been popped and replaced). Here, the second chance is based on the fact that if the element is seen “recently” its reference bit (bitref) is set to 1 (true). If it was not seen recently, we would not have set its reference bit (bitref) to 1 (true) and thus removed it. Hence, this is why, it is an approximation and not LRU nor FIFO.
Below is the implementation of the above approach:
Hits: 6 Faults: 6
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.