Design MRU type system
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-03-21
Problem Statement
Design a Most Recently Used (MRU) Cache that stores key-value pairs with a fixed capacity. Unlike LRU (Least Recently Used), the MRU cache evicts the most recently used item when capacity is full and a new item needs to be added.
Functional Requirements (FR)
Put / Insert
•Insert a key-value pair into the cache.
•If the cache is full, evict the most recently used item before inserting.
•If the key already exists, update its value and mark it as the most recently used.
Get
•Retrieve the value for a given key.
•If the key exists, mark it as the most recently used.
•If the key doesn’t exist, return null / -1.
Delete (Optional)
•Remove a key-value pair explicitly.
Capacity Management
•Cache has a fixed capacity.
•Eviction policy = MRU (remove the most recently used).
Non-Functional Requirements (NFR)
•Time Complexity → O(1) for get, put, delete operations.
•Space Efficiency → Store only up to capacity items.
•Concurrency (Optional) → Thread-safe operations for multi-threaded environment.
•Extensibility → Easy to switch eviction policy (MRU → LRU → LFU) if required.
Core Entities & Attributes
MRU: Cache
capacity: int
map: HashMap<Key, Node> (for O(1) lookup)
dll: DoublyLinkedList (to track usage order)
Node
•key, value
•prev, next pointers for quick reordering
Key Operations
•get(key) → returns value, updates key as most recently used.
•put(key, value) → insert/update, evict MRU if full.
•delete(key) → remove key if exists.
Design Considerations
Data Structures
•Use HashMap + DoublyLinkedList for O(1) operations.
•MRU is always at the head (or tail) of the list.
Eviction Logic
•On put when full → remove head/tail node depending on MRU pointer.
Patterns
•Can use Template Method / Strategy Pattern if supporting multiple eviction policies.
Example Walkthrough
Capacity = 3
•put(1, A) → Cache = {1=A}
•put(2, B) → Cache = {1=A, 2=B}
•put(3, C) → Cache = {1=A, 2=B, 3=C}
•get(2) → returns B, MRU=2
•put(4, D) → Evict MRU=2 → Cache = {1=A, 3=C, 4=D}
✅ This problem tests:
•HashMap + LinkedList O(1) operations.
•Understanding of cache eviction strategies (LRU vs MRU).
•Ability to design efficient, extensible system components.