Skip to main content
PreparationZone Logo
PrepZone

Coding Kata: Implement LRU

Build a thread-safe LRU with LinkedHashMap or a doubly-linked list — the pattern question paid courses assign.

Pass checkpoint below

Coding kata · Implement a fixed-size LRU cache

~14 min · type in your IDE or JShell, then check the answer

Complete an LRU cache with capacity 3 using LinkedHashMap. After each access, the least recently used key should be evicted when size exceeds capacity.

Java
public class LruCache<K, V> extends LinkedHashMap<K, V> {
  private final int capacity;

  public LruCache(int capacity) {
      // TODO: call super with accessOrder = true
      this.capacity = capacity;
  }

  @Override
  protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
      // TODO: return true when size() > capacity
      return false;
  }
}
Starter

Production note

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Test yourself

Answer these before moving on — recall is what makes it stick.