← All Exercises

Build an LRU Cache with LinkedHashMap

intermediatejava~20min

Background

LinkedHashMap maintains insertion or access order in constant time. A one-method override turns it into a compact LRU cache without a custom linked list.

Problem

Implement a fixed-capacity LRU cache backed by LinkedHashMap. Reads refresh recency, writes evict the least recently used entry, and capacity must be positive.

Input

A positive capacity and a sequence of get and put operations with string keys and integer values.

Output

After the operations, keySet reflects recency order and lookups return the stored value or null for an evicted key.

Sample tests

Sample 1

Input: capacity 2; put a=1, put b=2, get a, put c=3
Expected: keySet [a, c]
get(b) null
get(a) 1

Sample 2

Input: capacity 0
Expected: IllegalArgumentException: capacity must be positive

Your solution

Learning objective

Use access-ordered LinkedHashMap hooks, override eviction policy, and reason about recency updates on read.