Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update LRUCache.cpp #1327

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 61 additions & 69 deletions Data Structures/Cache/LRUCache.cpp
Original file line number Diff line number Diff line change
@@ -1,95 +1,87 @@
// Least recently used (LRU) cache (https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)
// Discards the least recently used items first


#include <iostream>
#include <unordered_map>
#include <queue>
#include <vector>
#include <list>

struct LRUCacheItem {
LRUCacheItem(int timestamp, int key): key(key), timestamp(timestamp) {}
LRUCacheItem(int timestamp, int key) : key(key), timestamp(timestamp) {}

int timestamp;
int key;
int timestamp;
int key;
};

// Custom comparator for priority queue (lower timestamp has higher priority)
struct LRUCacheComp {
bool operator()(const auto & item1,
const LRUCacheItem & item2) {
return item1.timestamp < item2.timestamp;
}
bool operator()(const LRUCacheItem& item1, const LRUCacheItem& item2) {
return item1.timestamp > item2.timestamp; // Reverse order for LRU
}
};

class LRUCache {
public:
LRUCache(int capacity) {
this -> capacity = capacity;
}

int get(int key) {
auto itCache = cache.find(key);

if (itCache != cache.end()) {
this->addToRecentUsed(key);
return itCache->second;
}
public:
LRUCache(int capacity) : capacity(capacity) {}

return -1;
}
int get(int key) {
auto itCache = cache.find(key);

void put(int key, int value) {
if (itCache != cache.end()) {
updateRecentUsed(key); // Update timestamp on get
return itCache->second;
}

cache[key] = value;

this->addToRecentUsed(key);

invalidateCache();
}
private:
void addToRecentUsed(int key) {
auto itRecentUsedLocation = recentUsedLocation.find(key);
if (itRecentUsedLocation != recentUsedLocation.end()) { //If exists
//erase old
recent_used.erase(itRecentUsedLocation->second);
}

//create new
recent_used.push_back(key);
auto it = recent_used.end();
--it;
//save location
recentUsedLocation[key] = it;
return -1;
}

void put(int key, int value) {
cache[key] = value;
updateRecentUsed(key);
invalidateCache();
}
void invalidateCache() {
if (cache.size() > capacity) {
int keyToRemove = recent_used.front();

cache.erase(keyToRemove);
recent_used.pop_front();
recentUsedLocation.erase(keyToRemove);
private:
void updateRecentUsed(int key) {
// Check if key exists in recent_used
auto itRecentUsedLocation = recentUsedLocation.find(key);
if (itRecentUsedLocation != recentUsedLocation.end()) {
// Erase the old entry from the priority queue
recent_used.erase(itRecentUsedLocation->second);
}

// Create a new entry with the current timestamp
recent_used.push(LRUCacheItem(time++, key)); // Use a global time counter
recentUsedLocation[key] = recent_used.end();
--recentUsedLocation[key]; // Move iterator back one step to point to the newly added element
}
}
std::unordered_map < int, int > cache;

std::list < int > recent_used;
std::unordered_map < int, std::list < int > ::iterator > recentUsedLocation;
void invalidateCache() {
if (cache.size() > capacity) {
int keyToRemove = recent_used.top().key; // Get the least recently used key
cache.erase(keyToRemove);
recent_used.pop();
recentUsedLocation.erase(keyToRemove);
}
}

int capacity;
std::unordered_map<int, int> cache;
std::priority_queue<LRUCacheItem, std::vector<LRUCacheItem>, LRUCacheComp> recent_used;
std::unordered_map<int, std::priority_queue<LRUCacheItem, std::vector<LRUCacheItem>, LRUCacheComp>::iterator> recentUsedLocation;
int capacity;
static int time; // Global timestamp counter for LRU order
};

int main() {
LRUCache cache(2 /* capacity */);
int LRUCache::time = 0; // Initialize static variable

cache.put(1, 1);
cache.put(2, 2);
std::cout << "> Get(1) = " << cache.get(1) << std::endl; // returns 1
cache.put(3, 3); // evicts key 2
std::cout <<"> Get(2) = " << cache.get(2) << std::endl; // returns -1 (not found)
cache.put(4, 4); // evicts key 1
std::cout <<"> Get(1) = " <<cache.get(1) << std::endl; // returns -1 (not found)
std::cout <<"> Get(3) = " <<cache.get(3) << std::endl; // returns 3
std::cout <<"> Get(4) = " <<cache.get(4) << std::endl; // returns 4
}
int main() {
LRUCache cache(2 /* capacity */);

cache.put(1, 1);
cache.put(2, 2);
std::cout << "> Get(1) = " << cache.get(1) << std::endl; // returns 1
cache.put(3, 3); // evicts key 2
std::cout << "> Get(2) = " << cache.get(2) << std::endl; // returns -1 (not found)
cache.put(4, 4); // evicts key 1
std::cout << "> Get(1) = " << cache.get(1) << std::endl; // returns -1 (not found)
std::cout << "> Get(3) = " << cache.get(3) << std::endl; // returns 3
std::cout << "> Get(4) = " << cache.get(4) << std::endl; // returns 4
}