What is LRU Cache? & It’s Implementation in Python

What is LRU Cache? & It’s Implementation in Python Computers have cache memory that temporarily stores the most frequently used data. Getting the data

 

What is LRU Cache? & It’s Implementation in Python





As LRU cache is used for fast extraction of data, so we need to write an optimal algorithm that runs in constant time. It’s tricky to find an optimal approach.


Suppose LRUCache class:
  • LRUCache(int capacity) Initialize size of the LRU cache.
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.



Now Let’s discuss different approaches from Brute Force to Optimized O(1) Approach.




About the Author

Software Engineer

1 comment

  1. LRU cache implementation using queue and hashing:
    To solve the problem follow the below idea:

    We use two data structures to implement an LRU Cache.

    Queue is implemented using a doubly-linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near the front end and the least recently used pages will be near the rear end.
    A Hash with the page number as key and the address of the corresponding queue node as value.
    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.
    If the required page is not in 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.

    Exa…
Enter your comments here...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
Site is Blocked
Sorry! This site is not available in your country.