LRU Cache implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-10-09

Problem Statement

Design and implement an LRU Cache that supports O(1) get and put operations and evicts the least recently used items when capacity is exceeded. Focus on efficient data structures, concurrency (optional), and memory management.


Functional Requirements (FR)


Cache Operations


•get(key) → Retrieve the value associated with the key.
•If key exists → return value and mark it as recently used.
•If key doesn’t exist → return -1 or null.
•put(key, value) → Insert or update a key-value pair.
•If cache is full → evict the least recently used item.
•If key exists → update value and mark as recently used.


Optional Features


•Thread-safe access for concurrent operations.
•Support for cache statistics (hitCount, missCount).
•TTL (time-to-live) for cache entries.


Non-Functional Requirements (NFR)


•Time Complexity → O(1) for get and put.
•Memory Efficiency → Minimal overhead for storing recency information.
•Scalability → Handle a large number of cache entries.
•Concurrency (Optional) → Safe access in multithreaded environments.


Core Entities & Attributes


CacheNode


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


LRUCache


•capacity → Maximum number of entries
•map → HashMap for key → CacheNode mapping
•head, tail → Pointers for most recently used (head) and least recently used (tail) nodes


Core Components


Doubly Linked List

•Maintains the order of usage.
•Head → Most recently used, Tail → Least recently used.
•Supports O(1) removal and insertion.

HashMap / Dictionary

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

LRUCache Class

•Combines HashMap and Linked List to implement get and put.
•Handles eviction, insertion, and recency updates.


APIs / Operations


Core APIs


•get(key: K): V → Returns value if key exists, else -1.
•put(key: K, value: V): void → Inserts or updates key-value pair. Evicts LRU if necessary.


Optional APIs


•remove(key: K): void → Remove a specific key.
•size(): int → Returns current number of entries.


LLD Design Goals


•Class Diagram → LRUCache containing CacheNode and internal HashMap.


Design Patterns:


•Composite / Linked List → For maintaining usage order.
•Decorator / Wrapper (Optional) → For TTL or stats tracking.
•Concurrency Handling (Optional) → Use locks or synchronized methods for thread safety.
•Trade-offs →1. Linked list + HashMap → O(1) operations but uses extra memory.

2.Using arrays reduces memory but increases operation complexity.


Solution

Comments