← All Exercises
LRU Cache with Eviction Log
intermediatejavascript
Background
LRU eviction is the default policy for CPU caches, CDN edge entries, and in-process memoization where bounded memory matters more than perfect retention.
Problem
Implement a fixed-capacity LRU cache. put inserts or refreshes a key, get returns the value or -1 and marks the key as most recently used, and when a put exceeds capacity the least recently used key is evicted. After processing all operations, output the get results and the eviction order.
Input
A JSON object {"capacity": number, "ops": array} where each op is {"op":"put","k":number,"v":number} or {"op":"get","k":number}.Output
A JSON object {"gets": number[], "evicted": number[]} with get results in call order (-1 for misses) and evicted keys in eviction order.Sample tests
Sample 1
Input: {"capacity":2,"ops":[{"op":"put","k":1,"v":1},{"op":"put","k":2,"v":2},{"op":"get","k":1},{"op":"put","k":3,"v":3},{"op":"get","k":2},{"op":"put","k":4,"v":4},{"op":"get","k":1},{"op":"get","k":3},{"op":"get","k":4}]}Expected: {"gets":[1,-1,-1,3,4],"evicted":[2,1]}Sample 2
Input: {"capacity":1,"ops":[{"op":"put","k":"a","v":10},{"op":"put","k":"b","v":20},{"op":"get","k":"a"},{"op":"get","k":"b"}]}Expected: {"gets":[-1,20],"evicted":["a"]}Your solution
Learning objective
Exploit Map insertion order to implement O(1) LRU recency tracking and eviction.