🌟 Introduction
In modern computing, caching is one of the most important techniques to make applications and systems faster. A cache stores frequently accessed data so future requests can be served quickly without recomputation. Among different caching strategies, the LRU Cache (Least Recently Used Cache) is one of the most popular. It removes the least recently used item whenever the cache reaches maximum capacity.
This article explains how to implement an LRU Cache with O(1) operations (get and put) using detailed diagrams. It covers both the theory and step-by-step examples, so even beginners can understand how it works.
🧩 What is an LRU Cache?
An LRU (Least Recently Used) Cache stores only a limited number of items. When it’s full and a new item must be added, it removes the item that has not been used for the longest time.
Example: Imagine a fridge that can only store 3 items. If it’s already full and you add something new, the food you haven’t touched for the longest time gets removed.
This ensures that the most useful and fresh data always stays in memory.
🔑 Key Operations in LRU Cache
get(key) → Returns the value if the key exists, otherwise returns -1.
put(key, value) → Inserts or updates a key-value pair. If the cache is full, it removes the least recently used item.
👉 The main challenge: Both operations must run in O(1) constant time.
⚙️ Data Structures Needed
To achieve O(1) time for both get and put, we use:
HashMap (Dictionary in Python) → For quick O(1) lookups to check if an item exists.
Doubly Linked List → To maintain the usage order (most recently used at the front, least recently used at the back).
By combining these:
The HashMap stores references to nodes in the Doubly Linked List.
The list tracks the order of usage, so we always know which item is least recently used.
🏗️ How the LRU Cache Works
1. Get Operation (get(key))
If the key exists:
Move the node to the front of the list (mark as most recently used).
Return the value.
If not found: return -1.
✅ Complexity: O(1).
. Put Operation (put(key, value))
If the key exists:
Update the value.
Move the node to the front.
If the key does not exist:
Create a new node.
Insert it at the front.
Add to HashMap.
If the cache is full, remove the last node (least recently used) from both the list and the HashMap.
Join the conversation! Your thoughts help the community grow.