M35 · Advanced Problem Solving

Combining Structures: LRU Cache, Randomized Set and Running Median

Some problems ask for a structure no library ships as such: a cache that evicts the least recently used entry, a set with random sampling, a stream that reports its median. Each is solved by combining two simpler structures so that every operation stays cheap. The binary heap lab above is one of the building blocks.

~40 minAdvancedC# · Python · Java · C++
Curriculum: M35 Advanced Problem Solving · 2 of 2 lessons available

You will be able to

  • Design an LRU cache from a hash map and a doubly linked list with O(1) get and put, and explain why neither structure alone is enough.
  • Build a set with O(1) insert, remove and uniform random sampling from an array and a hash map, using swap-with-last removal.
  • Maintain a running median with two heaps and keep their sizes balanced.
  • State the invariant that ties the two structures together and check it after every operation.
  • Know which built-ins already provide these designs (LinkedHashMap, OrderedDict) and where they stop helping.

Helpful before this lesson

  • M07 Linked Lists — Nodes and pointers: what O(1) insertion really requires, and the classic pointer techniques.
  • M10 Hash Tables and Sets — Hashing, collisions and load factor: why lookups are expected O(1) and when they are not.
  • M21 Heaps and Priority Queues — The array-backed heap, sift operations, O(n) heapify and heap sort.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

The idea

Each structure you know is fast at some operations and slow at others. A hash map finds a key in expected O(1) but has no order. A linked list moves a node anywhere in O(1) once you hold the node, but finding it is O(n). A heap gives the minimum in O(1) but cannot search. Combining two of them, with one pointing into the other, often gives a structure where every required operation is cheap.

The rule for every design below: write down the operations and their target costs first, then pick structures so that each operation is cheap in at least one of them, and keep an invariant that says how the two stay in sync.

The code in this lesson is pseudocode: these designs are combinations of the tested structures linked from each section, and of the built-ins listed at the end.

LRU cache: hash map + doubly linked list

Target: get(key) and put(key, value) in O(1); when full, put evicts the least recently used entry.

  • The doubly linked list keeps entries in recency order: most recent at the front, least recent at the back. Moving a node to the front or removing the back node is O(1).
  • The hash map maps each key to its list node, so finding the node is expected O(1).
  • Invariant: the map and the list contain exactly the same keys, and the list order is the order of last use.
Pseudocode
get(key):
    node = map.get(key)            # expected O(1)
    if node is missing: return not found
    list.move_to_front(node)       # O(1): unlink, relink at the front
    return node.value

put(key, value):
    if key in map:
        node = map[key]; node.value = value; list.move_to_front(node); return
    if size == capacity:
        old = list.remove_back()   # O(1): least recently used
        map.remove(old.key)        # the node stores its key for exactly this step
    node = list.push_front(key, value)
    map[key] = node

Why doubly linked? Removing a node from the middle needs its predecessor; a singly linked list would have to search for it (see the singly linked list lesson). Why store the key in the node? Eviction starts from the list and must delete the matching map entry.

Built-ins. Java's LinkedHashMap constructed with accessOrder = true keeps exactly this recency order, and overriding removeEldestEntry turns it into an LRU cache. Python's OrderedDict has move_to_end and popitem(last=False), and functools.lru_cache memoizes functions with this policy. C# and C++ have no ready-made LRU map: combine Dictionary<TKey, LinkedListNode<T>> with LinkedList<T>, or std::unordered_map<K, std::list<...>::iterator> with std::list, whose iterators stay valid when nodes are moved with splice.

LFU (least frequently used) adds a frequency per key and a list per frequency; the minimum frequency is tracked so eviction stays O(1). Same principle, one more layer.

Randomized set: array + hash map

Target: insert, remove and getRandom (uniformly random element) all in expected O(1).

  • An array gives O(1) random access, so getRandom picks a random index.
  • A hash map from value to its array index makes membership and lookup expected O(1).
  • Invariant: map[array[i]] == i for every index i.

Removing from the middle of an array is O(n) because of shifting (insert and delete in a fixed array). The trick is to swap the element with the last one, then pop the end:

Pseudocode
remove(x):
    if x not in map: return false
    i = map[x]
    last = array[array.length - 1]
    array[i] = last; map[last] = i     # move the last element into the hole
    array.pop_back(); map.remove(x)
    return true

Order is not preserved, which is fine for a set. Removing the last element itself also works: it is swapped with itself before being popped. Random number generators: Random.Shared.Next in C#, random.randrange in Python, ThreadLocalRandom.current().nextInt in Java and std::uniform_int_distribution with an engine in C++ (not rand() % n, which is biased).

Running median: two heaps

Target: add(x) in O(log n) and median() in O(1) over a stream.

  • A max-heap low holds the smaller half of the values; a min-heap high holds the larger half.
  • Invariant: every value in low ≤ every value in high, and low has the same number of elements as high or exactly one more.
  • The median is the top of low (odd count) or the average of both tops (even count).
Pseudocode
add(x):
    if low is empty or x <= low.top(): low.push(x) else: high.push(x)
    if low.size() > high.size() + 1: high.push(low.pop())
    if high.size() > low.size():     low.push(high.pop())

Each add does at most three heap operations, so O(log n). Step through pushes and pops in the binary heap lab above to see why each one costs O(log n). Watch the defaults: C# PriorityQueue and Python heapq are min-heaps, Java PriorityQueue is a min-heap by natural ordering, and C++ std::priority_queue is a max-heap by default (see the heaps lesson). Averaging two large integers can overflow in C#, Java and C++; compute a + (b - a) / 2 with care for the sign, or use a wider type.

How to check a combined structure

  1. Write the invariant as code and assert it after every operation in your tests.
  2. Compare with a slow model: a plain list scanned for the LRU order, a list for the randomized set, a sorted list for the median. Run random operation sequences against both.
  3. Test the boundaries: capacity 1 for the cache, removing the only element of the set, the first two values of the median stream.

That is how every structure in this lab is tested in C#, Python, Java and C++; the problem pages show the brute-force reference beside each solution.

Summary

Design Structures Invariant Costs
LRU cache hash map + doubly linked list same keys; list in order of last use get/put expected O(1)
Randomized set array + hash map map[array[i]] == i insert/remove/getRandom expected O(1)
Running median max-heap + min-heap low ≤ high; sizes differ by at most one add O(log n), median O(1)

The next step is the constraints-to-technique checklist, which decides when a custom structure is worth building at all.

Full implementation

The binary min-heap in four languages, each checked against one shared fixture of heapify, push, pop and peek sequences (including the exact heap array and errors on an empty heap), and 500 random operation sequences compared with PriorityQueue, heapq, java.util.PriorityQueue and std::priority_queue.

namespace Bekadan.Dsa.Examples.Heaps;
 
/// <summary>
/// Array-backed binary min-heap. Parent of i: (i - 1) / 2; children: 2i + 1, 2i + 2.
/// Push and Pop are O(log n), Peek is O(1), building from n items is O(n).
/// </summary>
public sealed class BinaryHeap<T>
{
    private readonly List<T> _items;
    private readonly Comparison<T> _compare;
 
    public BinaryHeap(Comparison<T>? compare = null) : this([], compare)
    {
    }
 
    /// <summary>Builds a heap from existing items with bottom-up heapify.</summary>
    public BinaryHeap(IEnumerable<T> items, Comparison<T>? compare = null)
    {
        _items = [.. items];
        _compare = compare ?? Comparer<T>.Default.Compare;
        for (int i = _items.Count / 2 - 1; i >= 0; i--) // indices Count/2 and up are leaves
            SiftDown(i);
    }
 
    public int Count => _items.Count;
 
    /// <summary>The heap array, index 0 first (for tests and teaching).</summary>
    public IReadOnlyList<T> Items => _items;
 
    public void Push(T value)
    {
        _items.Add(value); // the next free slot keeps the tree complete
        int i = _items.Count - 1;
        while (i > 0)
        {
            int parent = (i - 1) / 2;
            if (_compare(_items[i], _items[parent]) >= 0)
                break; // not smaller than its parent: done
            (_items[i], _items[parent]) = (_items[parent], _items[i]);
            i = parent;
        }
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        return _items[0];
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        T top = _items[0];
        int last = _items.Count - 1;
        _items[0] = _items[last]; // the last element fills the hole at the root
        _items.RemoveAt(last);
        if (_items.Count > 0)
            SiftDown(0);
        return top;
    }
 
    private void SiftDown(int i)
    {
        while (true)
        {
            int child = 2 * i + 1;
            if (child >= _items.Count)
                return; // a leaf
            if (child + 1 < _items.Count && _compare(_items[child + 1], _items[child]) < 0)
                child++; // the smaller child (the left one on ties)
            if (_compare(_items[child], _items[i]) >= 0)
                return; // not larger than its children: done
            (_items[i], _items[child]) = (_items[child], _items[i]);
            i = child;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Heaps/BinaryHeap.cs

"""Array-backed binary min-heap.
 
Parent of i: (i - 1) // 2; children: 2i + 1 and 2i + 2. push and pop are
O(log n), peek is O(1), building from n items is O(n). The standard library's
heapq module offers the same operations as functions on a plain list.
"""
 
from collections.abc import Iterable
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class BinaryHeap(Generic[T]):
    def __init__(self, items: Iterable[T] = ()) -> None:
        """Builds a heap from existing items with bottom-up heapify."""
        self._items: list[T] = list(items)
        for i in range(len(self._items) // 2 - 1, -1, -1):  # indices len // 2 and up are leaves
            self._sift_down(i)
 
    def __len__(self) -> int:
        return len(self._items)
 
    def items(self) -> list[T]:
        """A copy of the heap array, index 0 first (for tests and teaching)."""
        return list(self._items)
 
    def push(self, value: T) -> None:
        a = self._items
        a.append(value)  # the next free slot keeps the tree complete
        i = len(a) - 1
        while i > 0:
            parent = (i - 1) // 2
            if not a[i] < a[parent]:
                break  # not smaller than its parent: done
            a[i], a[parent] = a[parent], a[i]
            i = parent
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek from an empty heap")
        return self._items[0]
 
    def pop(self) -> T:
        a = self._items
        if not a:
            raise IndexError("pop from an empty heap")
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last  # the last element fills the hole at the root
            self._sift_down(0)
        return top
 
    def _sift_down(self, i: int) -> None:
        a = self._items
        while True:
            child = 2 * i + 1
            if child >= len(a):
                return  # a leaf
            if child + 1 < len(a) and a[child + 1] < a[child]:
                child += 1  # the smaller child (the left one on ties)
            if not a[child] < a[i]:
                return  # not larger than its children: done
            a[i], a[child] = a[child], a[i]
            i = child

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_heap.py

package dev.bekadan.dsa.heaps;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
 
/**
 * Array-backed binary min-heap (with respect to the comparator). Parent of i:
 * (i - 1) / 2; children: 2i + 1, 2i + 2. push and pop are O(log n), peek is
 * O(1), building from n items is O(n).
 */
public final class BinaryHeap<T> {
    private final List<T> items;
    private final Comparator<? super T> comparator;
 
    public BinaryHeap(Comparator<? super T> comparator) {
        this(List.of(), comparator);
    }
 
    /** Builds a heap from existing items with bottom-up heapify. */
    public BinaryHeap(Collection<? extends T> initial, Comparator<? super T> comparator) {
        this.items = new ArrayList<>(initial);
        this.comparator = comparator;
        for (int i = items.size() / 2 - 1; i >= 0; i--) { // indices size/2 and up are leaves
            siftDown(i);
        }
    }
 
    public int size() {
        return items.size();
    }
 
    /** The heap array, index 0 first (for tests and teaching). */
    public List<T> items() {
        return Collections.unmodifiableList(items);
    }
 
    public void push(T value) {
        items.add(value); // the next free slot keeps the tree complete
        int i = items.size() - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (comparator.compare(items.get(i), items.get(parent)) >= 0) {
                break; // not smaller than its parent: done
            }
            Collections.swap(items, i, parent);
            i = parent;
        }
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        return items.get(0);
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        T top = items.get(0);
        T last = items.remove(items.size() - 1);
        if (!items.isEmpty()) {
            items.set(0, last); // the last element fills the hole at the root
            siftDown(0);
        }
        return top;
    }
 
    private void siftDown(int i) {
        while (true) {
            int child = 2 * i + 1;
            if (child >= items.size()) {
                return; // a leaf
            }
            if (child + 1 < items.size() && comparator.compare(items.get(child + 1), items.get(child)) < 0) {
                child++; // the smaller child (the left one on ties)
            }
            if (comparator.compare(items.get(child), items.get(i)) >= 0) {
                return; // not larger than its children: done
            }
            Collections.swap(items, i, child);
            i = child;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/heaps/BinaryHeap.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// Array-backed binary min-heap (with respect to Less). Parent of i: (i - 1) / 2;
// children: 2i + 1, 2i + 2. push and pop are O(log n), top is O(1), building from
// n items is O(n). Note: std::priority_queue with std::less is a MAX-heap.
 
template <typename T, typename Less = std::less<>>
class BinaryHeap {
public:
    explicit BinaryHeap(Less less = {}) : less_(std::move(less)) {}
 
    // Builds a heap from existing items with bottom-up heapify.
    explicit BinaryHeap(std::vector<T> items, Less less = {}) : items_(std::move(items)), less_(std::move(less)) {
        for (std::size_t i = items_.size() / 2; i-- > 0;)  // i = size/2 - 1 down to 0; the rest are leaves
            sift_down(i);
    }
 
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] bool empty() const noexcept { return items_.empty(); }
 
    // The heap array, index 0 first (for tests and teaching).
    [[nodiscard]] const std::vector<T>& items() const noexcept { return items_; }
 
    void push(T value) {
        items_.push_back(std::move(value));  // the next free slot keeps the tree complete
        std::size_t i = items_.size() - 1;
        while (i > 0) {
            const std::size_t parent = (i - 1) / 2;
            if (!less_(items_[i], items_[parent]))
                break;  // not smaller than its parent: done
            std::swap(items_[i], items_[parent]);
            i = parent;
        }
    }
 
    [[nodiscard]] const T& top() const {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        return items_.front();
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        T result = std::move(items_.front());
        if (items_.size() > 1)
            items_.front() = std::move(items_.back());  // the last element fills the hole at the root
        items_.pop_back();
        if (!items_.empty())
            sift_down(0);
        return result;
    }
 
private:
    void sift_down(std::size_t i) {
        while (true) {
            std::size_t child = 2 * i + 1;
            if (child >= items_.size())
                return;  // a leaf
            if (child + 1 < items_.size() && less_(items_[child + 1], items_[child]))
                ++child;  // the smaller child (the left one on ties)
            if (!less_(items_[child], items_[i]))
                return;  // not larger than its children: done
            std::swap(items_[i], items_[child]);
            i = child;
        }
    }
 
    std::vector<T> items_;
    Less less_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_heap.hpp

References