Implement LRU Cache | Implement LRU Cache using HashMap & Doubly Linked List | Programming Tutorials

preview_player
Показать описание
Explained LRU Cache Implementation using HashMap and Doubly Linked List and it's Java Code.

In this tutorial, I have explained how to implement LRU cache get and put method in O(1) time complexity using HashMap and Doubly Linked List.

We have to design and implement a data structure for LRU (Least Recently Used) cache. It should support two operations get and put in O(1) time.

get(key) - Get the value if the key exists in a cache else returns -1.
put(key, value) - Insert the value if the key is already not present in a cache. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

The cache is Initialized with positive capacity.

LeetCode 30 Day Challenge
LeetCode Challenge Day 24 Question

Рекомендации по теме
Комментарии
Автор

Loved your explanation. Your tutorial is just awesome. Failed every other coding tutorial.

codingSpeedWithGK
Автор

Crystal Clear, Very nice explanation.

piyushsharma
Автор

very easy explanation of such complex problem.

sushmasinghSS
Автор

Well explained. Great work!! Keep it up :)

pmsb_
Автор

Is there use of doubly linked list here? I don't see it. Is the node itself by having next and prev, doing the job of the linkedlist?

lee
Автор

private int capacity;
HashMap<Integer, Integer> map=new HashMap<>();
Queue<Integer> queue=new LinkedList<>();
//HashMap<Integer, Integer> countMap=new HashMap<>();
public LRUCache(int capacity) {
this.capacity=capacity;
}

public int get(int key) {
if (map.containsKey(key)) {
if (queue.contains(key)) {
queue.remove(key);
queue.add(key);
return map.get(key);
}
}
return -1;
}

public void put(int key, int value) {

if(map.containsKey(key)){
queue.remove(key);
map.put(key, value);
queue.add(key);
}
else{
map.put(key, value);
queue.add(key);
}
}
else {
//when the cache reached the maximum capacity
//decide the LRU and remove from the map and mark it in queue and count map
if (map.containsKey(key)) {
queue.remove(key);
map.put(key, value);
queue.add(key);
} else {
int first = queue.remove();
map.remove(first);
map.put(key, value);
queue.add(key);
}
}
}


The easiest approach which i used to solve this problem and giving constant complexity for get and put operations.

praveenj
Автор

Can U plz upload the code, I am getting some errors so plz upload by night so that I can clear it asap

aishwaryahatti