How can we implement an LRU (Least Recently Used) cache using a LinkedList?

An LRU (Least Recently Used) cache stores a limited number of items and automatically removes the item that has not been accessed for the longest time when the cache reaches its capacity. Using a LinkedList, recently accessed elements are moved to the front, while the least recently used element remains at the end and can be removed when space is needed.

Key Points

Example

Consider a cache with a capacity of 3 storing pages A, B, and C. If page A is accessed, it becomes the most recently used item. When page D is added and the cache is full, page B (the least recently used item) is removed automatically.

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

class LRUCache<K, V> {

    private final int capacity;

    private final LinkedList<K> list = new LinkedList<>();
    private final Map<K, V> cache = new HashMap<>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public void put(K key, V value) {

        if (cache.containsKey(key)) {
            list.remove(key);
        } else if (cache.size() >= capacity) {

            K lruKey = list.removeLast();
            cache.remove(lruKey);
        }

        list.addFirst(key);
        cache.put(key, value);
    }

    public V get(K key) {

        if (!cache.containsKey(key)) {
            return null;
        }

        list.remove(key);
        list.addFirst(key);

        return cache.get(key);
    }
}

Interview Tip

A concise interview answer is: An LRU cache using a LinkedList keeps recently used items at the front and least recently used items at the end. On every access, the item is moved to the front, and when the cache reaches capacity, the last element is removed. In practice, a HashMap is used with the LinkedList to achieve efficient lookups and updates.

Last updated: 16 July 2026

Previous question: Consider the following scenario: You have two interfaces with the same default method signature but different method bodies. How would you resolve this diamond problem when a class implements both interfaces?

Next question: In what scenarios might a LinkedHashSet outperform a TreeSet, and vice versa?

More Core Java - Level IV (Advanced) interview questions

All Core Java - Level IV (Advanced) questions