← All Exercises
Generic LRU Cache with Eviction Log
intermediatetypescript
Background
LRU caches keep hot data in memory while bounding size. JavaScript Map preserves insertion order, so deleting and reinserting a key is a compact way to maintain recency without a linked list.
Problem
Implement LRUCache<K, V> with a positive capacity. get returns the value and promotes the key; set inserts or updates and evicts the least recently used entry when full; delete removes a key; entries returns pairs from least to most recently used. Every eviction must be recorded with its value.
Input
A JSON object with capacity and ops, where each op is set (key, value), get (key), or delete (key).
Output
A JSON object with gets (values or null), evicted pairs in order, and final entries from LRU to MRU.
Sample tests
Sample 1
Input: {"capacity":2,"ops":[{"op":"set","key":"a","value":1},{"op":"set","key":"b","value":2},{"op":"get","key":"a"},{"op":"set","key":"c","value":3},{"op":"get","key":"b"}]}Expected: {"gets":[1,null],"evicted":[["b",2]],"entries":[["a",1],["c",3]]}Sample 2
Input: {"capacity":1,"ops":[{"op":"set","key":"a","value":1},{"op":"set","key":"b","value":2}]}Expected: {"gets":[],"evicted":[["a",1]],"entries":[["b",2]]}Sample 3
Input: {"capacity":2,"ops":[{"op":"set","key":"a","value":1},{"op":"set","key":"b","value":2},{"op":"set","key":"a","value":3}]}Expected: {"gets":[],"evicted":[],"entries":[["b",2],["a",3]]}Your solution
Learning objective
Use Map insertion order to implement LRU semantics with typed keys and values.