Design LRU Cache (original) (raw)

Last Updated : 03 Jan, 2025

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

Working-of-LRU-Cache-copy-2

How to design your own LRU Cache?

Input: [LRUCache cache = new LRUCache(2) , put(1 ,1) , put(2 ,2) , get(1) , put(3 ,3) , get(2) , put(4 ,4) , get(1) , get(3) , get(4)]
Output: [1 ,-1, -1, 3, 4]
Explanation: The values mentioned in the output are the values returned by get operations
.

Table of Content

[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.

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.

[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.

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