Command Palette

Search for a command to run...

← All patterns

Pattern · Design

Combine Structures to Design

Pair a hash map (fast lookup) with a list, heap or tree (fast ordering) to meet every operation's time limit.

Time O(1) per operation for LRU · Space O(capacity)

Taught in Module 40: Designing Data Structures (arrives in wave 4)

Think of it like this

A library with a catalogue (find any book instantly) and a returns trolley in order (know which came back last).

Clues that point here

  • → "Design a class" with several operations
  • → Each operation has a required complexity, often O(1)
  • → LRU, LFU, time-based key-value store
  • → Min stack, randomised set

Not this pattern when

  • ✕ One structure already supports every operation fast enough

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Combine Structures to Design · template
class LRUCache {
    private final int capacity;
    private final LinkedHashMap<Integer, Integer> map;

    LRUCache(int capacity) {
        this.capacity = capacity;
        this.map = new LinkedHashMap<>(16, 0.75f, true);   // access order
    }
    int get(int key) { return map.getOrDefault(key, -1); }
    void put(int key, int value) {
        map.put(key, value);
        if (map.size() > capacity) map.remove(map.keySet().iterator().next());  // least recent
    }
}

Common versions

  • LRU cache
  • LFU cache
  • Min stack
  • Insert delete getRandom O(1)
  • Time-based key-value store

Practice problems with this pattern