The Wayback Machine - https://web.archive.org/web/20240910061934/https://www.geeksforgeeks.org/design-a-data-structure-for-lru-cache/
Open In App

Design LRU Cache

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Design a data structure for LRU Cache. It should support the following operations: get and put.

  • get(key) – Returns the value of the given key if it exists in the cache; otherwise, returns -1.
  • put(key, value) – Inserts or updates the key-value pair in the cache. If the cache reaches capacity, remove the least recently used item before adding the new item.

[Naive Approach – 1] LRU Cache using an Array of Nodes – O(n) Time and O(n) Space:

The idea is to implement using an array to store nodes, where each node holds a key-value pair. The primary operations, get and put, are performed with O(n) time complexity due to the need to search through the array. The size of the array will be equal to the given capacity of the cache. 

  • put(int key, int value)
    • If the cache is full, find the node with the oldest timestamp (least recently used) and replace this node with the new key and value.
    • else, simply add the new node to the end of the array.
    • Time Complexity: O(n) (because you might have to search for the oldest node)
  • get(int key)
    • Search through the array for the node with the matching key.
    • If found, return its value , else return -1.
    • Time Complexity: O(n) (because you might have to check every node)

We initialize an array of size equal to that of our cache. Here each data element stores extra information to mark with an access time stamp. It shows the time at which the key is stored. We will use the timeStamp to find out the least recently used element in the LRU cache.

C++
// C++ class to represent a node in an LRU Cache
class LRUCache {
  public:
    int key;
    int value;
    int timeStamp;

    LRUCache(int k, int data, int time) {
        key = k;
        value = data;
        timeStamp = time;
    }
};
Java
//Java class to represent a node in an LRU Cache
public class LRUCache {
    int key;
    int value;
    int timeStamp;

    public LRUCache(int key, int value, int timeStamp) {
        this.key = key;
        this.value = value;
        this.timeStamp = timeStamp;
    }
}
Python
#Python class to represent a node in an LRU Cache
class LRUCache:
    def __init__(self, key, value, time_stamp):
        self.key = key
        self.value = value
        self.time_stamp = time_stamp
C#
//C# class to represent a node in an LRU Cache
public class LRUCache {
    public int Key;
    public int Value;
    public int TimeStamp;

    public LRUCache(int key, int value, int timeStamp) {
        Key = key;
        Value = value;
        TimeStamp = timeStamp;
    }
}
JavaScript
//Javascript class to represent a node in an LRU Cache
class LRUCache {
    constructor(key, value, timeStamp) {
        this.key = key;
        this.value = value;
        this.timeStamp = timeStamp;
    }
}

[Naive Approach – 2] LRU Cache using Singly Linked List – O(n) Time and O(n) Space:

The approach to implement an LRU (Least Recently Used) cache involves using a singly linked list to maintain the order of cache entries.

  • get operation: The cache searches for the node with the requested key by traversing the list from the head. If the key is found, the node is moved to the head of the list to mark it as the most recently used, and its value is returned. else, returns -1. This operation has a time complexity of O(n) because it may require scanning through the entire list.
  • put operation: The cache inserts a new key-value pair at the head of the list if the cache has not reached its capacity. If the key already exists, the corresponding node is found and updated, then moved to the head. When the cache reaches its capacity, the least recently used element, which is located at the tail of the list, is removed. The time complexity for this operation is also O(n) due to the traversal and reordering steps involved.

[Expected Approach] LRU Cache using Doubly Linked List and Hashing- O(1) Time and O(1) Space:

The basic idea behind implementing an LRU (Least Recently Used) cache using a key-value pair approach is to manage element access and removal efficiently through a combination of a doubly linked list and a hash map.

  • When adding a new key-value pair, insert it as a new node at the head of the doubly linked list. This ensures that the newly added key-value pair is marked as the most recently used.
  • If the key is already present in the cache, get the corresponding node in the doubly linked list using hashmap, update its value and move it to the head of the list.
  • When the cache reaches its maximum capacity and a new key-value pair needs to be added, remove the node from hashmap as well as from the tail in the doubly linked list.

Plese refer to codes LRU Cache implementation using Doubly Linked Lists for implementation.



Previous Article
Next Article

Similar Reads

LRU Cache in Python using OrderedDict
LRU (Least Recently Used) Cache discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least
4 min read
Is LRU the best Cache Eviction Policy?
Whether LRU (Least Recently Used) is the best eviction policy depends on the specific requirements and characteristics of the system. LRU (Least Recently Used) is often considered a good eviction policy in the following cases: 1. Temporal LocalityWhen there is a temporal locality in the access patterns, meaning that recently accessed items are like
2 min read
LRU Cache - Complete Implementation
What is LRU Cache?Cache replacement algorithms are efficiently designed to replace the cache when the space is full. The Least Recently Used (LRU) is one of those algorithms. As the name suggests when the cache memory is full, LRU picks the data that is least recently used and removes it in order to make space for the new data. The priority of the
5 min read
How Cache Locks can be used to overcome Cache Stampede Problem?
Caching is a technique used to store data temporarily in a high-speed storage layer, such as memory or a dedicated cache, to reduce the latency and load on a primary data source, such as a database or a web service. Important Topics for Cache Locks to overcome Cache Stampede ProblemCache Stampede ProblemLocking MechanismCache Population ProcessLock
5 min read
Cache Invalidation and the Methods to Invalidate Cache
Cache invalidation is a state where we push away the data from the cache memory when the data present is outdated so do we perform this operation of pushing back/flushing the cache otherwise this still data will result in inconsistency of data. When cached data gets stale or inaccurate, cache invalidation is the process of removing or updating it..
6 min read
Design Distributed Cache | System Design
Designing a Distributed Cache system requires careful consideration of scalability, fault tolerance, and performance. This article explores key architectural decisions and implementation strategies to create an efficient, high-performance caching solution. Important Topics for Distributed Cache Design What is caching?What is Distributed Caching?Req
9 min read
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 value
15+ min read
Implementation of Least Recently Used (LRU) page replacement algorithm using Counters
Prerequisite - Least Recently Used (LRU) Page Replacement algorithm Least Recently Used page replacement algorithm replaces the page which is not used recently. Implementation: In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference
8 min read
Program for Least Recently Used (LRU) Page Replacement algorithm
Prerequisite: Page Replacement AlgorithmsIn operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly
14 min read
Page Faults in LRU | Implementation
LRU uses the concept of paging for memory management. A page replacement algorithm is needed to decide which page needs to be replaced when the new page comes in. Whenever a new page is referred to and is not present in memory, the page fault occurs and the Operating System replaces one of the existing pages with a newly needed page. LRU is one suc
15 min read
Cache Stampede or Dogpile Problem in System Design
The Cache Stempede or Dogpile Problem is defined as a situation where the system receives multiple requests for a cached resource simultaneously for which the cache has already expired or has become invalid. Cache Stampede or Dogpile Problem in System Design is a phenomenon that can occur in systems that rely on caching to improve performance. As a
6 min read
Cache Eviction Policies | System Design
Cache eviction refers to the process of removing data from a cache to make room for new or more relevant information. Caches store frequently accessed data for quicker retrieval, improving overall system performance. However, caches have limited capacity, and when the cache is full, the system must decide which data to remove. The eviction policy d
11 min read
Cache Eviction vs. Expiration in System Design
Caching plays a pivotal role in enhancing speed and efficiency. However, effective cache management involves understanding the differences between cache eviction and expiration. While both mechanisms aim to manage cached data, they operate differently and serve distinct purposes. What is Cache Eviction?Cache eviction is a process in which a cache m
2 min read
Cold and Warm Cache in System Design
In the world of system design, caching plays a pivotal role in enhancing performance, reducing latency, and optimizing resource utilization. Understanding the importance of caching, particularly the concepts of cold and warm caches, is essential for designing efficient systems. This article delves into the fundamentals of caching, explores the diff
6 min read
Cache Write Policies - System Design
Cache write policies play a crucial role in determining how data is written to the cache and main memory in computing systems. These policies are essential for improving system performance and ensuring data consistency. This article explains what cache write policies are, explains various cache write policies in detail, and discusses how to choose
9 min read
Why Arrays have better cache locality than Linked list?
What is a Cache locality?Cache locality refers to the property of computer programs where they tend to access a small, specific set of data repeatedly in a short period of time. By keeping this frequently accessed data in a small, fast memory region called a cache, the program can speed up its execution time. This is because accessing data from the
9 min read
Asynchronous Caching Mechanisms to Overcome Cache Stampede Problem
Caching is a critical component in modern software systems, serving as an effective means to reduce latency and improve system performance. Asynchronous caching is a caching mechanism that allows data to be stored and retrieved in a non-blocking, asynchronous manner. This means that when data is requested, the system doesn't wait for the cache to p
4 min read
How a Cache Stampede Caused One of Facebook's Biggest Outages
On September 23, 2010, Facebook experienced one of its most severe outages to date, affecting hundreds of thousands of users internationally. The website online remained inaccessible for over 4 hours, causing extensive disruption and frustration. The root reason for the outage changed into a cache stampede, a phenomena that happens when a large num
4 min read
Least Frequently Used (LFU) Cache Implementation
Least Frequently Used (LFU) is a caching algorithm in which the least frequently used cache block is removed whenever the cache is overflowed. In LFU we check the old page as well as the frequency of that page and if the frequency of the page is larger than the old page we cannot remove it and if all the old pages are having same frequency then tak
9 min read
How to Implement Reverse DNS Look Up Cache?
Reverse DNS look up is using an internet IP address to find a domain name. For example, if you type 74.125.200.106 in browser, it automatically redirects to google.in. How to implement Reverse DNS Look Up cache? Following are the operations needed from cache: Add an IP address to URL Mapping in cache.Find URL for a given IP address. One solution is
15+ min read
Redis cache in Java using Jedis
Jedis is the client library for Java in Redis that provides all the Redis features in applications based on Java. It is thread-safe and supports all the data types that Redis supports. It also provides the Jedis pooling which helps in creating a 3pool of connections that can be reused to enhance the performance. Redis cache is a popularly used in-m
3 min read
Redis Cache
As we all know caching refers to storing frequently used or dealt-up data in temporary high-speed storage to reduce the latency of a system. So we do the same when happens inside a Redis cluster. Therefore, Redis Cache supercharges application performance by utilizing in-memory data caching. By storing frequently accessed data in memory, Redis Cach
7 min read
How to Implement Forward DNS Look Up Cache?
We have discussed implementation of Reverse DNS Look Up Cache. Forward DNS look up is getting IP address for a given domain name typed in the web browser. The cache should do the following operations : 1. Add a mapping from URL to IP address 2. Find IP address for a given URL. There are a few changes from reverse DNS look up cache that we need to i
13 min read
Cache Oblivious Algorithm
Cache oblivious is a way of achieving algorithms that are efficient in arbitrary memory hierarchies without the use of complicated multi-level memory models. Cache oblivious algorithms are algorithms that use asymptotically optimal amounts of work, move data asymptotically optimally among multiple levels of cache, and indirectly use processor cache
14 min read
Why is Cache Invalidation Difficult?
Caching is a technique used to store copies of frequently accessed or computed data to reduce latency and improve performance. However, ensuring that cached data remains valid and up-to-date can be complex. Below are the reasons why is Cache Invalidation Difficult. Complexity of DependenciesIn a dynamic web application, content often depends on mul
2 min read
When Should a Cache be Invalidated?
A Cache should be invalidated when the data it contains becomes outdated or stale. Here are some common scenarios when cache invalidation is necessary. 1. Data UpdatesWhen the underlying data that is cached is modified or updated, the corresponding cached data should be invalidated to ensure that the cache reflects the most recent changes. 2. Expir
2 min read
Types of Cache
Cache plays an important role in enhancing system performance by temporarily storing frequently accessed data and reducing latency. Understanding the various types of cache is crucial for optimizing system design and resource utilization. Important Topics for the Types of Cache What is Cache?Importance of CachingTypes of CacheCPU CacheDisk CacheWeb
13 min read
Cache oblivious kd-Tree
Cache-oblivious kd-tree data structures are a great utility that performs multi-dimensional orthogonal range searching. One of the salient terms of kd trees is binary space partitioning which periodically subdivides space into two convex sets by using hyperplanes as splitting. This article focuses on discussing the following topics in detail- Cache
9 min read
What are Cache Locks?
In computer architecture, cache locks play a crucial role as shared data access coordinators in systems with several cores and processors. Cache locks are essential for preserving program accuracy and averting data corruption because they are made to guarantee data consistency and prevent race situations. Ensuring data integrity and optimizing syst
10 min read
Cache-Aside Pattern
The "Cache-Aside Pattern" is a way to manage data caching to improve system performance. When an application needs data, it first checks the cache. If the data is there a cache hit, it is used right away. If not a cache miss, the application fetches the data from the main database, stores a copy in the cache, and then uses it. This pattern helps re
15+ min read