Skip to lesson

Designing complex composite data structures

Complex systems often require multi-faceted data structures that combine hash maps with doubly linked lists, heaps, or arrays to satisfy competing O(1) constraints.

Deconstructing composite requirements: hash maps + pointers

A composite data structure combines two simple structures so that each covers the other's weakness.

Java
static class Node {    int key, val;    Node prev, next;                           // the list keeps the order}Map<Integer, Node> map = new HashMap<>();      // key -> node: O(1) lookupNode head = new Node(), tail = new Node();     // sentinels around the list
void moveToFront(Node n) {                     // O(1): the map gave us the node    n.prev.next = n.next;    n.next.prev = n.prev;    n.next = head.next; n.prev = head;    head.next.prev = n; head.next = n;}

A cache, for example, needs O(1) key lookups like a hash map, but must also track order (access recency or frequency) so it can evict the correct item when capacity is exceeded. A hash map that points into a doubly linked list gives both:

Every single basic data structure has fundamental trade-offs. An array provides O(1) random access by index, but deleting an arbitrary element takes O(N) time because elements must shift. A linked list allows O(1) insertion and deletion once you hold a pointer to the node, but searching for a key takes O(N) time. A hash map gives O(1) average lookup and deletion by key, but possesses no intrinsic concept of element order or minimum/maximum. To overcome these individual limitations, engineers combine multiple primitive structures into a composite data structure. In this pattern, a secondary data structure (such as a doubly linked list, an array list, or a balanced binary search tree) maintains the desired order, while a primary hash map stores references or indices directly into the secondary structure. This hybrid design allows both O(1) lookup and O(1) structural modification.

Designing the LFU Cache: frequencies and doubly linked lists

An LFU (Least Frequently Used) cache evicts the key with the lowest access frequency. When multiple keys tie for the lowest frequency, it evicts the least recently used key among them. Both get(key) and put(key, value) operations must run in strictly O(1) average time.

Example 1 · LFU cache with a scan on eviction, brute force: O(N) put when full, O(1) get

LfuScanDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class LfuScanDemo {    private final int capacity;    private final Map<Integer, Integer> values = new HashMap<>();    private final Map<Integer, Integer> uses = new HashMap<>();    private final Map<Integer, Integer> lastUsed = new HashMap<>();    private int clock = 0;
    LfuScanDemo(int capacity) { this.capacity = capacity; }
    int get(int key) {        if (!values.containsKey(key)) return -1;        uses.put(key, uses.get(key) + 1);        lastUsed.put(key, ++clock);        return values.get(key);    }
    void put(int key, int value) {        if (!values.containsKey(key) && values.size() == capacity) {            int victim = -1;            for (int k : values.keySet()) {              // scan every key to find the least used                if (victim == -1 || uses.get(k) < uses.get(victim)                        || (uses.get(k).equals(uses.get(victim)) && lastUsed.get(k) < lastUsed.get(victim))) {                    victim = k;                }            }            values.remove(victim);            uses.remove(victim);            lastUsed.remove(victim);        }        values.put(key, value);        uses.merge(key, 1, Integer::sum);        lastUsed.put(key, ++clock);    }
    public static void main(String[] args) {        LfuScanDemo lfu = new LfuScanDemo(2);        lfu.put(1, 10);        lfu.put(2, 20);        System.out.println("get(1): " + lfu.get(1));        lfu.put(3, 30);        System.out.println("get(2) after eviction: " + lfu.get(2));        System.out.println("get(3): " + lfu.get(3));    }}
Output
get(1): 10
get(2) after eviction: -1
get(3): 30

What this code does

  • uses counts how often each key was read or written; lastUsed breaks ties between equal counts.
  • When the cache is full, the loop over values.keySet() finds the victim in O(N).
  • It prints the same results as the frequency-list version.

Example 2 · LFU cache with frequency lists, optimal: O(1) get and put

LfuCacheDemo.javaJava
import java.util.*;
public class LfuCacheDemo {    static class Node {        int key, val, freq = 1;        Node prev, next;        Node(int key, int val) { this.key = key; this.val = val; }    }
    static class DLList {        Node head = new Node(0, 0), tail = new Node(0, 0);        int size = 0;        DLList() { head.next = tail; tail.prev = head; }        void add(Node n) {            n.next = head.next; n.prev = head;            head.next.prev = n; head.next = n;            size++;        }        void remove(Node n) {            n.prev.next = n.next; n.next.prev = n.prev;            size--;        }        Node removeLast() {            if (size == 0) return null;            Node last = tail.prev;            remove(last);            return last;        }    }
    private int capacity, minFreq = 0;    private Map<Integer, Node> keyMap = new HashMap<>();    private Map<Integer, DLList> freqMap = new HashMap<>();
    public LfuCacheDemo(int capacity) { this.capacity = capacity; }
    public int get(int key) {        if (!keyMap.containsKey(key)) return -1;        Node n = keyMap.get(key);        updateFreq(n);        return n.val;    }
    public void put(int key, int val) {        if (capacity == 0) return;        if (keyMap.containsKey(key)) {            Node n = keyMap.get(key);            n.val = val;            updateFreq(n);            return;        }        if (keyMap.size() == capacity) {            DLList minList = freqMap.get(minFreq);            Node evicted = minList.removeLast();            keyMap.remove(evicted.key);        }        Node n = new Node(key, val);        keyMap.put(key, n);        minFreq = 1;        freqMap.computeIfAbsent(1, k -> new DLList()).add(n);    }
    private void updateFreq(Node n) {        DLList oldList = freqMap.get(n.freq);        oldList.remove(n);        if (oldList.size == 0 && n.freq == minFreq) minFreq++;        n.freq++;        freqMap.computeIfAbsent(n.freq, k -> new DLList()).add(n);    }
    public static void main(String[] args) {        LfuCacheDemo lfu = new LfuCacheDemo(2);        lfu.put(1, 10);        lfu.put(2, 20);        System.out.println("get(1): " + lfu.get(1)); // freq(1)=2, freq(2)=1        lfu.put(3, 30); // evicts key 2 (lowest freq 1)        System.out.println("get(2) after eviction: " + lfu.get(2));        System.out.println("get(3): " + lfu.get(3));    }}
Output
get(1): 10
get(2) after eviction: -1
get(3): 30

What this code does

  • Keys 1 and 2 start with frequency 1.
  • get(1) increments frequency of key 1 to 2.
  • put(3) exceeds capacity 2, so key 2 with lowest frequency (1) is evicted. get(2) returns -1, confirming successful O(1) LFU eviction.
  • Why faster: each frequency has its own linked list and the cache tracks the minimum frequency, so the victim is found without scanning every key.

To achieve O(1) runtime, we maintain three data structures:

  1. keyToVal and keyToFreq hash maps for O(1) key lookups.
  2. freqToKeys: a map from each frequency count to a Doubly Linked List of keys sharing that frequency. The DLL maintains the recency order among tied keys.
  3. minFreq: an integer tracking the minimum access frequency currently present in the cache. When get(key) is called, we look up the key, increment its frequency from f to f + 1, remove the key from the DLL at freqToKeys[f], and add it to the front of freqToKeys[f + 1]. If freqToKeys[f] becomes empty and minFreq == f, we increment minFreq. When put(key, value) causes capacity overflow, we evict the least recently used node from freqToKeys[minFreq] in O(1) time and reset minFreq to 1 for the newly inserted key.

Designing TimeMap and RandomizedSet: binary search and swap-to-back

Another classic composite challenge is the Time-Based Key-Value Store (TimeMap), supporting set(key, value, timestamp) and get(key, timestamp) returning the value with the largest timestamp <= query timestamp. Because timestamps arrive in strictly chronological order, we store entries in a Map<String, List<Entry>>. Each key maps to an ArrayList of (timestamp, value) pairs. Because the list is naturally sorted by timestamp, get(key, timestamp) uses binary search to find the predecessor entry in O(log K) time.

A second widely requested design is RandomizedSet, which supports insert(val), remove(val), and getRandom() all in O(1) average time. A standard hash set cannot pick a uniformly random element in O(1) because bucket distributions are non-contiguous. An ArrayList allows O(1) getRandom() via random index, but removing an arbitrary value takes O(N) due to shifting.

The solution combines an ArrayList<Integer> with a Map<Integer, Integer> storing val -> indexInArrayList. When insert(val) is called, append val to the array list and record its index in the map. When remove(val) is called, look up its index, swap val with the LAST element of the array list, update the map entry for the swapped element, and pop the last element from the array list in O(1) time. This swap-to-back trick completely eliminates array shifting.

Example 3 · Randomised set backed only by a list, brute force: O(N) insert and remove

ListOnlySetDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Random;
public class ListOnlySetDemo {    private final List<Integer> items = new ArrayList<>();    private final Random random = new Random();
    boolean insert(int value) {        if (items.contains(value)) return false;         // contains scans the list: O(N)        items.add(value);        return true;    }
    boolean remove(int value) {        return items.remove(Integer.valueOf(value));     // search and shift: O(N)    }
    int getRandom() {        return items.get(random.nextInt(items.size()));    }
    public static void main(String[] args) {        ListOnlySetDemo set = new ListOnlySetDemo();        System.out.println("Insert 10: " + set.insert(10));        System.out.println("Insert 20: " + set.insert(20));        System.out.println("Insert 10 again: " + set.insert(10));        System.out.println("Remove 10: " + set.remove(10));        System.out.println("Random remaining: " + set.getRandom());    }}
Output
Insert 10: true
Insert 20: true
Insert 10 again: false
Remove 10: true
Random remaining: 20

What this code does

  • contains() and remove(Object) scan the list from the start, and remove also shifts later elements.
  • getRandom() is fast because a list can be read by position.
  • It prints the same results as the list-and-map version.

Example 4 · Randomised set with a list and a map, optimal: O(1) average operations

RandomizedSetDemo.javaJava
import java.util.*;
public class RandomizedSetDemo {    private List<Integer> list = new ArrayList<>();    private Map<Integer, Integer> map = new HashMap<>();    private Random rand = new Random(42);
    public boolean insert(int val) {        if (map.containsKey(val)) return false;        map.put(val, list.size());        list.add(val);        return true;    }
    public boolean remove(int val) {        if (!map.containsKey(val)) return false;        int idx = map.get(val);        int lastVal = list.get(list.size() - 1);
        list.set(idx, lastVal);        map.put(lastVal, idx);
        list.remove(list.size() - 1);        map.remove(val);        return true;    }
    public int getRandom() {        return list.get(rand.nextInt(list.size()));    }
    public static void main(String[] args) {        RandomizedSetDemo set = new RandomizedSetDemo();        System.out.println("Insert 10: " + set.insert(10));        System.out.println("Insert 20: " + set.insert(20));        System.out.println("Insert 10 again: " + set.insert(10));        System.out.println("Remove 10: " + set.remove(10));        System.out.println("Random remaining: " + set.getRandom());    }}
Output
Insert 10: true
Insert 20: true
Insert 10 again: false
Remove 10: true
Random remaining: 20

What this code does

  • 10 is inserted at index 0.
  • 20 is inserted at index 1.
  • Duplicate insert of 10 returns false. Removing 10 swaps 20 into index 0 and pops the end in O(1). Only 20 remains, so getRandom() returns 20.
  • Why faster: the map finds an element's position instantly, and removal swaps it with the last element so nothing shifts.

Example 5 · Time-based store with a backwards scan, brute force: O(N) per get

TimeScanDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class TimeScanDemo {    private final Map<String, List<int[]>> times = new HashMap<>();    private final Map<String, List<String>> values = new HashMap<>();
    void set(String key, String value, int time) {        times.computeIfAbsent(key, k -> new ArrayList<>()).add(new int[]{time});        values.computeIfAbsent(key, k -> new ArrayList<>()).add(value);    }
    String get(String key, int time) {        if (!times.containsKey(key)) return "";        List<int[]> t = times.get(key);        for (int i = t.size() - 1; i >= 0; i--) {        // walk back from the newest entry: O(N)            if (t.get(i)[0] <= time) return values.get(key).get(i);        }        return "";    }
    public static void main(String[] args) {        TimeScanDemo tm = new TimeScanDemo();        tm.set("foo", "bar", 1);        System.out.println("get(foo, 1): " + tm.get("foo", 1));        System.out.println("get(foo, 3): " + tm.get("foo", 3));        tm.set("foo", "bar2", 4);        System.out.println("get(foo, 4): " + tm.get("foo", 4));        System.out.println("get(foo, 0): " + tm.get("foo", 0));    }}
Output
get(foo, 1): bar
get(foo, 3): bar
get(foo, 4): bar2
get(foo, 0): 

What this code does

  • set() appends the timestamp and the value to two parallel lists.
  • get() walks back from the newest entry until it finds one at or before the requested time.
  • It prints the same four lines as the binary search version.

Example 6 · Time-based store with binary search, optimal: O(log N) per get

TimeMapDemo.javaJava
import java.util.*;
public class TimeMapDemo {    static class Entry {        int timestamp;        String val;        Entry(int timestamp, String val) {            this.timestamp = timestamp;            this.val = val;        }    }
    private Map<String, List<Entry>> map = new HashMap<>();
    public void set(String key, String value, int timestamp) {        map.computeIfAbsent(key, k -> new ArrayList<>()).add(new Entry(timestamp, value));    }
    public String get(String key, int timestamp) {        if (!map.containsKey(key)) return "";        List<Entry> list = map.get(key);        int low = 0, high = list.size() - 1;        String ans = "";        while (low <= high) {            int mid = (low + high) / 2;            if (list.get(mid).timestamp <= timestamp) {                ans = list.get(mid).val;                low = mid + 1;            } else {                high = mid - 1;            }        }        return ans;    }
    public static void main(String[] args) {        TimeMapDemo tm = new TimeMapDemo();        tm.set("foo", "bar", 1);        System.out.println("get(foo, 1): " + tm.get("foo", 1));        System.out.println("get(foo, 3): " + tm.get("foo", 3));        tm.set("foo", "bar2", 4);        System.out.println("get(foo, 4): " + tm.get("foo", 4));        System.out.println("get(foo, 0): " + tm.get("foo", 0));    }}
Output
get(foo, 1): bar
get(foo, 3): bar
get(foo, 4): bar2
get(foo, 0): 

What this code does

  • At timestamp 1, foo has value bar.
  • At timestamp 3, the latest timestamp <= 3 is 1, so value is bar.
  • At timestamp 4, foo is updated to bar2. At timestamp 0, no timestamp exists <= 0, returning empty string.
  • Why faster: timestamps arrive in increasing order, so each key's list is sorted and binary search halves the range at every step.

Design trade-offs: concurrency, memory overhead, and cache locality

While composite data structures deliver outstanding theoretical time complexities, they introduce real-world engineering trade-offs. The first trade-off is memory overhead. Pointer-rich structures like doubly linked lists allocate separate node objects on the heap. In Java, each object header incurs 12 to 16 bytes of overhead plus references. If an LFU cache holds millions of entries, node allocations create significant garbage collection pressure and fragment heap memory.

The second trade-off is CPU cache locality. Contiguous arrays (like ArrayList or flat tables) benefit from hardware prefetching because adjacent elements reside on the same CPU cache line. Conversely, linked list nodes are scattered across memory, causing frequent CPU cache misses.

Finally, composite structures complicate thread safety. Because an operation updates both a hash map and a linked list or array, intermediate states are inconsistent. If one thread reads while another thread has updated the map but not yet updated the linked list, data corruption occurs. In concurrent systems, operations must be synchronized using ReadWriteLocks or atomic compare-and-swap (CAS) primitives.

Next step

Check your understanding

10 quick questions