LRU Cache implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-01-26

Problem Statement

Design and implement an LRU Cache that supports fast retrieval and eviction of least recently used items when the cache reaches capacity. Focus on efficiency, thread-safety (optional), and O(1) operations for both get and put.


Functional Requirements (FR)


Cache Operations


•get(key) → Returns value for a key if it exists, else returns -1 or null.
•put(key, value) → Inserts a new key-value pair.
•If cache is full, evict the least recently used item.
•If key already exists, update its value and mark it as recently used.
•Maintain access order so that least recently used items can be efficiently identified.


Optional Features


•Thread-safe operations for concurrent access.
•Support TTL (time-to-live) for cache entries.
•Support custom eviction policies in addition to LRU (e.g., LFU).


Non-Functional Requirements (NFR)


•Time Complexity → O(1) for get and put.
•Memory Efficiency → Store only necessary metadata for access order.
•Scalability → Handle large number of cache entries efficiently.
•Concurrency (Optional) → Safe access by multiple threads.


Core Entities & Attributes


CacheNode


•key, value
•prev, next → pointers for doubly-linked list


LRUCache


•capacity → Maximum number of entries
•map → Key → CacheNode mapping (HashMap / Dictionary)
•head, tail → Pointers to maintain recency order (most recently used at head, least recently used at tail)


Core Components


HashMap / Dictionary

•Provides O(1) access to cache nodes by key.

Doubly Linked List

•Maintains recency order:
•Move accessed node to head.
•Evict node from tail when capacity is exceeded.

LRUCache Class

•Integrates the hashmap and linked list to provide efficient get/put operations.


APIs / Operations


Core APIs


•get(key: K): V → Returns value if key exists, else returns -1. Moves accessed node to head.
•put(key: K, value: V) → Inserts or updates key-value pair. Moves node to head; evicts tail if capacity exceeded.
•remove(key: K) (Optional) → Remove a specific key.
•size(): int → Returns current number of cache entries.


LLD Design Goals


•Class Diagram → LRUCache containing CacheNode and internal HashMap.


Design Patterns:


•Composite / Linked List → Maintain order of nodes.
•Decorator / Wrapper (Optional) → For TTL or additional features.
•Concurrency Handling (Optional) → Use locks, synchronized methods, or concurrent hashmap.
•Trade-offs → 1. Using linked list + hashmap gives O(1) but consumes extra memory. 2. Using array or queue reduces memory but increases operation complexity.


Solution

Comments