An efficient LRU (Least Recently Used) Cache implementation in C++ using
Doubly Linked List + Hash Map, supporting O(1) time complexity for both
get() and put() operations.
Design a cache system with a fixed capacity that removes the least recently used item when the cache is full.
This implementation combines two data structures:
- Stores
key → Node* - Enables O(1) access to cache entries
- Maintains usage order
- Most Recently Used → Head
- Least Recently Used → Tail
The cache class controls:
- Capacity
- Eviction
- Memory ownership
- Returns value if key exists
- Moves node to front (most recently used)
- Returns
-1if key not found
- Updates value if key exists
- Inserts new key if not
- Evicts least recently used key if capacity is full
| Operation | Complexity |
|---|---|
get() |
O(1) |
put() |
O(1) |
| Space | O(N) |
g++ -std=c++17 LRU_Cache/main.cpp \
LRU_Cache/LRUCache.cpp \
Data_Structures/LinkedList/DoublyLinkedList.cpp \
-o lru
./lru
## Sample Output
10
-1
30
-1
30
40